Rajagopal Subramanian Rajagopal Subramanian - 9 days ago 4
JSON Question

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

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

Answer

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;

    });
});
Comments