How can i use JSON stringify in Angular? - angularjs

i'm newbie to Angular. I'm trying to get Json data which written like that :
id:1,
name: "Friends",
type: "Group",
Now, i know i can't use this kind of data unless i add double quotes - like that (it's the only way it is working):
"id":1,
"name": "Friends",
"type": "Group",
What is the best way to parse JSON in Angular?
I've tried to combine JS , but it didn't work :
app.controller('contacts', function ($scope,$http,$log) {
$http.get('http://localhost/Angular-Http-exercise/db.json')
.then(function(response) {
$scope.myData = function() {
return JSON.stringify(response.data)
};
$log.info(response.data.name);
});
});

You can use angular.fromJson and angular.toJson for that purpose:
scope.myData = function(){
return angular.fromJson(response.data);
}
However JSON is a global variable and you should have access to it, since angular uses the same.
https://docs.angularjs.org/api/ng/function/angular.fromJson
https://docs.angularjs.org/api/ng/function/angular.toJson

Roy, your question is What is the best way to parse JSON in Angular? JSON will not differ from one framework/language to another and there's no best way to write JSON.
If you want to see if your JSON is formatted correctly check out tools like: https://jsonformatter.curiousconcept.com/

Related

I want to Pass value to JSON in angularjs

Please give me some example of $http.post. I am new in AngularJS. I want to update a JSON file while retrieving information from user. I want to update values but unable to update a JSON file.
My JSON file is data.json.
{ var app=angular.module("APP",[]);
app.controller("APPController", function ($scope, $http){
$scope.add = function(){
var dataObj={ model:$scope.addModel,
car: [$scope.option1, $scope.option2, $scope.option3, $scope.option4],
type: $scope.Type};
$http.post("data.json",dataObj)
.success(function(res){console.log("success"+res.records)}) .error(function(res){console.log("error")});
};
});
}
and here is my data.json file
{
"records": [
{
"model" : "car model",
"car" : ["num1","num2","num3","num4"],
"type" : "mode type"
},
{
"model" : "car model",
"car" : ["num1","num2","num3","num4"],
"type" : "mode type"
},
]
}
You can pass the data object in 2nd param of the $http.post() method.
I am confused to get the exact context of update JSON. But if you want to update the existing variable array in your controller which you are using in view from the response, you can do it it JavaScript way.
Here is a working example for the same. This might help.
JSFiddle: http://jsfiddle.net/ashishanexpert/zvcx5z38/2/
You don't POST data on a JSON file, you make the POST API call to a server.
You can GET data from a JSON file.
I suggest you read through Angular's POST documentation first.

How to use $resource in Angular to work with a RESTful api

I'm trying to add some basic CRUD functionality to MEAN stack. I've created a RESTful service that works and I'm confused about how to wire it all up. I can get it to work, but I want to make sure I'm doing things the best way and not creating an unnecessary hack.
My api route for a single Person is like this:
// Find one person
app.get('/api/person/:id', function(req, res) {
Person.find ( {_id: req.params.id },
function(err, data){
res.json(data);
}
)});
// Find group of people
app.get('/api/person', function(req, res) {
// use mongoose to get all people in the database
Person.find(function(err, data) {
res.json(data);
});
This seems to work in that if I go to a URI with an ID, as in localhost://3000/api/person/23423434, I see JSON data like this:
[
{
"_id": "532d8a97e443e72ef3cb3e60",
"firstname": "Horace",
"lastname": "Smith",
"age": 33
}
]
This tells me the basic mechanics of my RESTful api are working. Now I'd like to display that data with angular in a template like so:
<h3>{{ person.firstname + ' ' + person.lastname }} </h3>
To do that, I just need to create a $scope.person object with get() or query(). Here's the relevant part of my app:
angular.module('crudApp', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/api/person/:id',
{
templateUrl: 'partials/person.html',
controller: 'PersonCtrl'
});
}])
.factory('Person', function($resource){
return $resource('api/person/:id', { id: '#_id'});
})
.controller('PersonCtrl', function($scope, $routeParams, Person){
$scope.person = Person.get( { id: $routeParams.id } ); // Having trouble here!
});
The trouble I'm having is that get() fails with an error (Error: [$resource:badcfg]). On the other hand, if I use Person.query(), I get back an array, which means I need to change my template to the following:
<h3>{{ person[0].firstname + ' ' + person[0].lastname }} </h3>
This works, but seems strange and isn't like what I've seen in angular tutorials. The only other solution I've found is to set $scope.person in a callback:
Person.query({ id: $routeParams.id }, function(person){
$scope.person = person[0];
});
This works with my original unmodified template. Is it the best or right way to work with RESTful apis like this? Is there a better way?
Answer: the answer is in comment below. My problem is that api is using Person.find() but should be using Person.findOne( { _id: req.params.id }); Using findOne() returns a single object.
Your api should look like this:
route -> '/api/person/:id'
return single person
route -> '/api/person'
return array of persons
then if you want to get by id, you shall use get method, or if you want to get all persons, you should use query method. Your mistake is that you shall return single object when getting by id

Angular Factory Manipulating Data (CRUD) with function in the Factory

I have a simple Angular App that uses a factory to pull a list of items from a "JSON" file. Eventually this will be connected to a database but for now I'm starting with just pulling from a static file. The JSON file contains an array of items. I'm really trying to understand how do I get a reference to my data in the factory after the promise has been returned to the controller.
My Factory is setup as follows:
angular.module("myApp").factory("ServiceTypeFactory", ['$http', function ($http ) {
return {
ServiceTypes: function () {
return $http.get('json/servicetypes.json').success
(
function (data) {
return data;
});
},
find: function (id) {
return _.findWhere(data, {ID:id}); // Not sure how to get access to the data
}
}
}]);
This works great I can share the Factory across multiple controllers. The part I'm missing is how do I reference a specific array item from my json file and update it in my controller. I'm not following how to get a reference to the actual data so when I modify the item in one controller it the change would be reflected in another controller.
In both of my controllers I have the following code to get a reference to the data initially.
var popService = function (data) {
$scope.ServiceTypes = data;
}
// IF at ANY time the Service Types have not been loaded we will populate them.
if (typeof $scope.ServiceTypes === "undefined") {
ServiceTypeFactory.ServiceTypes().success(popService);
}
My understanding is my $scope.ServiceTypes has really a reference to the data. How do I back in my factory in a function get access to the actual single source of my data. I get that the factory returns the data with functions an object but I'm missing how to reference this data back in my factory to manipulate it. In the future I want to perform CRUD operations on it for the time being I'm just trying to work out the mechanics.
What my JSON file looks like:
{
"serviceTypes": [
{
"ID": "1001",
"ServiceTypeName": "111111",
"Description": "aaaaaaa"
},
{
"ID": "1002",
"ServiceTypeName": "222222",
"Description": "bbbbbbb"
},
{
"ID": "1003",
"ServiceTypeName": "3333333",
"Description": "ccccccc"
},
{
"ID": "1004",
"ServiceTypeName": "444444",
"Description": "dddddddd"
},
{
"ID": "1005",
"ServiceTypeName": "5555555",
"Description": "eeeeeee"
}
]
}
Just needed to clean the code up a little. Watching a couple of quick example on egghead.io made it clear.

AngularJS Resource won't work with an array

I am trying to use AngularJS to retrieve a JSON array (a list of strings). I have created a Resource, like so:
packageResource.factory('Package', ['$resource', function($resource) {
return $resource('/static/package.json', {}, {
'get': {
method: 'GET',
transformResponse: function (data) {
return angular.fromJson(data)
},
isArray: true
}
});
}]);
And my Controller like this:
MainController = [
'$scope', 'Package', function($scope, Saved, Rules) {
$scope.package = (Package.get());
}
];
And my template:
<ul>
<li ng-repeat="item in package">{{item}}</li>
</ul>
<p> {{package}}</p>
I expect it to display a list of all the items in the package.json array, and then, for testing, I added the {{package}} and would expect it to print the contents, but instead, I get:
{}
{}
{}
{}
{"0":"s","1":"r","2":"d"}
The JSON file contains the following:
[1,3,6,"srd"]
However, if I change my package.json to an object, it works perfectly. For example:
{
"author": "John",
"name": "project",
"version": 1
}
And of course, change isArray to false. I get:
John
project
1
So it appears that something can't handle an array, and mangles it into an object. I am having trouble figuring out what - all the Angular documentation shows Resource and Scope working with arrays, and it doesn't make since for them not to. I explicitly added the isArray: true flag to my Resource definition, but no luck.
I am using Angular version 1.0.8. I am a complete newbie, so it may be something painfully obvious, but I have been trying to get this to work for over a day now.
isArray=true means your json data looks like an array of objects, aka, a list. Each item in the array must be an object. so your json data needs to be [{name:value,name2:value2},{etc},{etc}].
isArray=false means your json data is a singular object.
This is the standard way of representing the restful data that $resource was designed to work with.

Backbone Model not compatible with underscore and ASP.NET MVC Web API Controller?

This is a two stage problem when working with backbone.js and a web api controller.
I have a simple web api controller that returns a JSON string, in fiddler the result looks like this:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
I use the following code to fetch a user from my web api
var user = new Usermodel({ id: "1" });
user.fetch({
success: function (u) {
console.log(u.toJSON());
}
});
now my backbone user object looks like this
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
When I try to bind this backbone model object to my view template that looks like this
<form>
<input type="text" value="<%=Heading%>" />
<input type="submit" value="Save" />
</form>
i get, Heading is undefined but when I use id it binds just fine? It seems like underscore does not like the backbone model object and just want a plain JSON object just like the one I get from my web api?
The second problem with this is that when I save my model with user.save({ Heading: "my new heading }); the payload to my web api is the backbone model which is completely wrong because my api expects a user object like this to be sent to the server:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
and not the backbone model with the real object wrapped inside. Is it possible to solve so that underscore can handle backbone models and tell backbone to only send the payload that my end point expects?
You may be able to solve the problem by following these steps:
In addition to using fiddler to inspect your response, look at the response on the network tab of Chrome Developer Tools. If the response does not look like this, then your web api is not returning a valid json response, the problem is most likely within your web api. You need to get/provide more information about your web api to solve the problem. Verify that the response looks like this:
After verifying that the response from the web api is correct, check out the following jsfiddle I modified:
http://jsfiddle.net/J83aU/23/
Fix your client side code referencing the example I have provided.
Properly instantiate the Backbone objects.
Call the view.render function at the correct step, after the response is received from the server.
Make sure that the main content div is actually rendered before creating a view which depends on it for the 'view.el' property.
Declare the 'view.el' property properly, with a string rather than jQuery object.
Use development Backbone and underscore to enable debugging, an important concept when learning to use open source frameworks such as Backbone.
Use jsfiddle's echo/json api to mock a valid ajax json response, exactly as described in step 1.
The following json example you submitted is not even valid json, if you update your question with valid json example, it would be easier to solve the problem. It is unlikely that Backbone created this non-json structure and more likely that you have submitted it here incorrectly.
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
Finally, try to provide a screenshot of the http headers or something for the problem that is occurring when you call model.save().
Read over the Backbone documentation for model.save() and make sure you are doing everything just as the example provided.
You may be able to workaround Backbone's funky save function by forcing your attributes into POST parameters using ajax options:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var saveView = Backbone.View.extend({
events:{
'click #saveSubmitButton':'submit'
},
submit:function (event) {
event.preventDefault();
var view = this,
attributes = $('#saveForm').serializeObject();
this.model.save(attributes, {
data:attributes,
processData:true,
success:function (model) {
//....
}
});
},
render:function () {
//.......
}
});
The attributes property of your model should be unaltered. Send those to your template call:
var MyModel = Backbone.Model.extend();
var newModel = new MyModel({
"$type": "MvcApplication.Models.Article, MvcApplication",
"Heading":"The heading"
});
var html = _.template(templateVar, newModel.attributes);
In your templateVar, which is your templated markup, you should be able to reference $type and Heading directly.
If you have a look at the jsFiddle through a debugger like Firebug you can see that the way you construct the model's URL is not working out, because the forward slash gets encoded. Can you try to modify your model declaration to this:
var Usermodel = Backbone.Model.extend({
url: function () {
return '/api/page/articles/' + this.get('id');
}
});
var user = new Usermodel({
id: '85'
});
And see if you still get the same JSON. Basically if you don't have a Backbone.sync override you are using built-in retrieval that for one shouldn't produce invalid JSON.

Resources