How to add JSON object into JSON array using angular JS? - json

I have problem while parsing single json object.
Assume that the below data get from server
{
"root": {
"data": [
{
"name": "Raj",
"age": "22"
},
{
"name": "Janu",
"age": "22"
}
]
}
}
And my script is
Script.js
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
$scope.myDatas = response.root;
});
});
HTML
<div ng-repeat="i in myDatas.data">
Name: {{i.name}}
Age: {{i.age}}
</div>
I have no problem while the response data is more than 1. But If the response data is 1 then the json will be:
{
"root": {
"data": {
"name": "Raj",
"age": "22"
}
}
}
How to generically parse these json data ?
PLNKR: http://plnkr.co/edit/W4YK6BDtIBfVhnPpHVm1?p=preview

You need just slight change, check type of responsedata.root.data. If it is not array, convert it to array. Here is your code becomes.
Here is plnkr
// Code goes here
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !(response.root.data instanceof Array )){
response.root.data=[response.root.data]
}
$scope.myDatas = response.root;
});
});

You can normalize incoming data to always be an array. It's convenient to use Array.prototype.concat method for this:
$http.get("singledata.json")
.success(function(response) {
$scope.myDatas = response.root;
$scope.myDatas.data = [].concat($scope.myDatas.data);
});
Demo: http://plnkr.co/edit/UUWtDBK8qID1XoYeMXhu?p=preview

I would check if data is an array or not, and if not, just ammend the data to be an array:
Like this:
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !angular.isArray(response.root.data)){
var object = response.root.data;
response.root.data = [];
response.root.data.push(object);
}
$scope.myDatas = response.root;
});

You can check the whether the data is array or not. If not then you create the array as. Check this code its working.
For controller:
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
var data = response.root.data;
if(data.constructor === Array){
$scope.myDatas = data;
}else{
$scope.myDatas = new Array(data);
}
});
});
For html:
<div ng-repeat="i in myDatas">
Name: {{i.name}}
Age: {{i.age}}
</div>
Hope this helps.

Related

Trouble Parsing JSON object in Angular

I am having trouble in parsing the JSON object, not sure where I am wrong?
Here is HTML:
<div ng-controller="MyCtrl">
<div ng-repeat="user in _users" ng-init="myInfo=parJson(user.response)">{{myInfo.docs[0].FIRST_NAME}}</div>
</div>
Here is Angular:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.getName = function(user) {
return "Names";
};
$scope._users = [{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME":"John",
"LAST_NAME" : "Smith"}]
}
}];
$scope.parJson = function(json) {
return JSON.parse(json);
}
}
myApp.controller("MyCtrl",MyCtrl);
From the code i can see that "user.response" is already a JSON object, you don't need to parse it again. One thing you can do if you are not sure if your response is a JSON object or JSON string you can add a check in you "parJson" function
$scope.parJson = function(json) {
if(typeof json != "object")
return JSON.parse(json);
else
return json;
}
You have extra comma after QTime property. Remove it and try again. Use JSON Lint to validate your json.

How to convert Backbone fetched object to proper Handlebars JSON Object?

Currently I have an issue with getting back a proper JSON object I'm fetching with Backbone fetch() and putting it into a Handlebars template.
See below my code, I have made a ugly workaround for now to test my Backend API
When converting to JSON with *.toJSON(), it just adds an extra object in-between and I don't need this extra object
Object [0]
--> books
----> Object [0]
------> Array of book
--------> book
--------> cities
JSON
{
"books": [
{
"book": 00001,
"cities": [
"TEST"
]
},
{
"book": 00002,
"cities": [
"TEST"
]
},
{
"book": 00003,
"cities": [
"TEST"
]
}
],
"more": true
}
JavaScript
var Book = Backbone.Model.extend({
default: {
book: 0,
cities: ["TEST1", "TEST2", "TEST3"]
},
url: function () {
return ".list.json";
}
});
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json"
});
var BooksView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render');
this.collection = new Books();
this.collection.fetch();
this.source = $('.e-books-template').html();
// Use an extern template
this.template = Handlebars.compile(this.source);
var self = this;
this.collection.fetch({
success: function () {
self.render();
},
error: function () {
console.log("ERROR IN BooksView");
}
});
},
render: function() {
var collect = JSON.stringify(this.collection);
collect = collect.slice(1, -1);
var html = this.template($.parseJSON(collect));
this.$el.html(html);
}
});
var booksView = new BooksView({ });
$(document).ready(function(){
booksView.$el = $('.e-books-content');
});
A Backbone collection expects an array of models but your JSON provides an object with the array under a books key. Parse the server response to format the data :
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json",
parse: function(data) {
return data.books;
}
});
Pass your data to your template via http://backbonejs.org/#Collection-toJSON ,
// directly as an array in your template
var html = this.template(this.collection.toJSON());
// under a books key
var html = this.template({
books: this.collection.toJSON()
});
And a demo http://jsfiddle.net/nikoshr/8jdb13jg/

Angular load local json and get arrays

I am new in angular and I am trying to load json file and repeat it on index file but can get through that json to get the arrays for repeat
app.js
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
var obj = {content:null};
$http.get('test.json').success(function(data) {
obj.content = data;
});
console.log(obj);});
json file
{"data":
{"result":"success","customers_list":[
{"Chat":
{
"name": "John",
"town":"LA"
}},
{"Chat":
{
"name": "Peter",
"town":"NY"
}}],"message":"The function is correctly"}}
I would like to get the name and town , any ideas how to go through data-> customer_list untill I get something like:
$scope.loadChat =[
{
"name": "John",
"town":"LA"
},
{
"name": "Peter",
"town":"NY"
}
];
You can use the built in map function:
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
$scope.loadChat = [];
$http.get('test.json').success(function(data) {
$scope.loadChat = data.data.customers_list.map(function(chat) {
return chat.Chat;
});
});
});
The map() method creates a new array with the results of calling a
provided function on every element in this array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
tYou can display the name and town looping trough content.data.customers_list with ng-repeat.
controller:
chatApp.controller('userCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('test.json').success(function(data) {
$scope.content = data;
});
}]);
html:
<div ng-repeat="user in content.data.customers_list">
{{user.Chat.name}} {{user.Chat.town}}
</div>

How to make couple of JSON Get request Angular JS

This is an interesting question. I'm using a simple JSON Get request to get all the competetions according to date, and show result as a list.
the JSON response is kind of :
[
{
"id":33
"competition":565
},
{
"id":66
"competition":345
}
]
Then I should make another json request to get the name of each json item :
myserver.com/{id}
which look like :
{
"name":"Serie A"
}
I want to show a list of all the names of the competetions I have on the first json request according to date.
here is my angular js code for showing the list of a simple JSON request :
<div ng-controller="customersCtrl">
<ul>
<li ng-repeat="m in matches">
{{ m.id }}
</li>
</ul>
</div>
<script>
var app = angular.module('starter', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://Myserver.com/matches?date=2015-05-19")
.success(function (response) {$scope.matches = response;});
</script>
You can iterate through the matches and get the names with a new call:
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://myserver.com/matches?date=2015-05-19")
.success(function (response) {
$scope.matches = response;
for (var i = 0; i < response.length; i++) {
setName($scope.matches, i);
}
});
var setName = function (matches, index) {
$http.get("http://myserver.com/" + matches[index].id)
.success(function (response) {
matches[index].name = response.name;
});
}
});
Below code will first fetch all the competitions and then using their ids it will fetch names all the events parallely. it will give all the competition with details in one go only.
Warning: If you have large numbers of all competition then it will make same number of calls to get competition details all of them.
app.service('competition', function($http) {
this.getAllCompetitions = function() {
var baseUrl = 'http://Myserver.com';
return $http.get(baseUrl + '/matches?date=2015-05-19')
.then(function(allCompetitions) {
/* sample `data`
[
{
"id":33
"competition":565
},
{
"id":66
"competition":345
}
]
*/
var qArr = [];
allCompetitions.forEach(function(competition, index) {
var promise = $http.get(baseUrl + '/' + competition.id)
.then(function(competitionDetail) {
/* sample `competitionDetail`
{
"name":"Serie A"
"competition":565
}
*/
return {
competitionDetail: competitionDetail,
index: index
};
});
aArr.push(promise);
});
return $q.all(qArr).then(function(listOfData) {
listOfData.forEach(function(item) {
allCompetitions[item.index] = angular.extend(allCompetitions[item.index], item.competitionDetail);
});
return allCompetitions;
});
});
}
});

Backbone toJSON not rending

I am a complete n00b to Backbone.js, and have only been working with it for a few days. I am attempting to fetch JSON data to populate the model, and in this scenario I have two models that I need to generate. Here is the sample JSON I have been working with:
JSON
{
"status": "200",
"total": "2",
"items":
[{
"id": "1",
"name": "Here is another name",
"label": "Label for test",
"description": "A description for more information.",
"dataAdded": "123456789",
"lastModified": "987654321"
},
{
"id": "2",
"name": "Name of item",
"label": "Test Label",
"description": "This is just a long description.",
"dataAdded": "147258369",
"lastModified": "963852741"
}]
}
Backbone JS
// MODEL
var Service = Backbone.Model.extend({
defaults: {
id: '',
name: '',
label: '',
description: '',
dateAdded: '',
dateModified: ''
}
});
var service = new Service();
// COLLECTION
var ServiceList = Backbone.Collection.extend({
model: Service,
url: "./api/service.php",
parse: function(response) {
return response.items;
}
});
//
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
success: function() {
console.log("Working!");
console.log(serviceList.length);
},
error: function() {
console.log("Failed to fetch!");
}
});
// VIEW for each Model
var ServiceView = Backbone.View.extend({
el: $('.widget-content'),
tagName: 'div',
template: _.template($('#service-template').html()),
initialize: function() {
this.collection.bind("reset", this.render, this);
},
render: function() {
console.log(this.collection);
this.$el.html('');
var self = this;
this.collection.each(function(model) {
self.$el.append(self.template(model.toJSON()));
});
return this;
}
});
//
var serviceView = new ServiceView({
collection: serviceList
});
console.log(serviceView.render().el);
html
<div class="widget-content">
<!-- Template -->
<script type="text/template" id="service-template">
<div><%= name %></div>
</script>
</div>
When I console log the serviceList.length I get the value 2, so I believe the JSON object is fetched successfully. I also get the "Working!" response for success too. However, in the view I am showing an empty object, which gives me an empty model.
I am still trying to understand the best way to do this too. Maybe I should be using collections for the "items" and then mapping over the collection for each model data? What am I doing wrong? Any advice or help is greatly appreciated.
I can see two problems. First, you want to remove serviceList.reset(list). Your collection should be populated automatically by the call to fetch. (In any case the return value of fetch is not the data result from the server, it is the "jqXHR" object).
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
success: function(collection, response) {
console.log("Working!");
// this is the asynchronous callback, where "serviceList" should have data
console.log(serviceList.length);
console.log("Collection populated: " + JSON.stringify(collection.toJSON()));
},
error: function() {
console.log("Failed to fetch!");
}
});
// here, "serviceList" will not be populated yet
Second, you probably want to pass the serviceList instance into the view as its "collection". As it is, you're passing an empty model instance into the view.
var serviceView = new ServiceView({
collection: serviceList
});
And for the view, render using the collection:
var ServiceView = Backbone.View.extend({
// ...
initialize: function() {
// render when the collection is reset
this.collection.bind("reset", this.render, this);
},
render: function() {
console.log("Collection rendering: " + JSON.stringify(this.collection.toJSON()));
// start by clearing the view
this.$el.html('');
// loop through the collection and render each model
var self = this;
this.collection.each(function(model) {
self.$el.append(self.template(model.toJSON()));
});
return this;
}
});
Here's a Fiddle demo.
The call serviceList.fetch is made asynchronously, so when you try console.log(serviceList.length); the server has not yet send it's response that's why you get the the value 1, try this :
var list = serviceList.fetch({
success: function() {
console.log(serviceList.length);
console.log("Working!");
},
error: function() {
console.log("Failed to fetch!");
}
});