I'm getting a json using $http.$get, but to it be "compatible" with Angular, I'm having to convert it this way:
$http.get('/api/v1.0/plans').
success(function(data) {
var plans = [];
for(var propertyName in data)
{
if (data.hasOwnProperty(propertyName))
{
plans.push(data[propertyName]);
}
}
$scope.plans = angular.fromJson(data);
});
But, of course, I think this would be the way to go in this case, as shown in docs:
$http.get('/api/v1.0/plans').
success(function(data) {
$scope.plans = data;
});
I can see the difference between the objects, I just don't know how to fix it:
data (not accepted by angular)
Object {alfa: Object, beta: Object, delta: Object, omega: Object}
plans (converted and accepted by angular)
[Object, Object, Object, Object]
Could you, please, tell what I'm doing wrong?
You need to elaborate a bit more about what kind of "compatible" problem you refered to in your first sentence. As far as I know, both JSON representations work just fine in Angular for me.
I believe the question here boils down to how the data will be used after being set to $scope.plans. If you are trying to use ng-repeat with $scope.plans afterward, then how you iterate will differ slightly depending whether the data you receive is a JSON object or JSON array.
For JSON object, you use
<tr ng-repeat="(name, plan) in plans">
<td> {{name}} </td> <td> {{ plan | json }} </td>
</tr>
For JSON array, you use
<tr ng-repeat="plan in plans">
<td> {{$index}} </td> <td> {{ plan | json }} </td>
</tr>
Of course, for plan specified in HTML snippets above, you can access object inner fields with dot notation as usual (i.e., {{plan.title}}, {{plan.description}}, etc.). {{plan | json}} just converts JSON object into string so you can see object content directly in HTML.
For details on how to use ngRepeat, you can read more at https://docs.angularjs.org/api/ng/directive/ngRepeat
In case a (Object {alfa: Object, beta: Object, delta: Object, omega: Object} your api return object so you have to define plans as a object not array that should works
$scope.plans = {}; // <-object
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
in case you api will return array of object you have to define plans as a array ie:
$scope.plans = []; // <-array
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
Please see bin here
Related
An API gives me json response like this:
[{"version": "v3.5"}, {"setup": true}, {"address": "e7d398b"}, {"connected": true}, {"active": true}, {"id": "ce7143"}, {"genuine": true}]
As you can see, this is a list of objects. I tried parsing it like this using quicktype generated model class-
List<Result>.from(result.map((x) => Result.fromJson(x)));
But it's failing since each of the objects are of different types.
I think I have to convert each of the objects in the array one by one to Dart classes and add it to an Array.
So I tried this (I am using dio) -
final result = response.data;
var b = List.empty(growable: true);
result.map((x) => b.add(x));
But it's not working.
How can I atleast access the elements of the array?
Solved
Inspired by the accepted answer, I was able to generate corresponding Dart Class. Never thought can looping through a map is possible, IDE was not giving any clue.
final result = response.data;
Map<String, dynamic> map = {};
for (var e in result) {
map.addAll(e);
}
final finalResult = Result.fromJson(map);
return finalResult;
As Randal Schwartz mentioned above, there is no JSON you can not parse with Dart.
In your case, you have a List of Map objects. What you can do is:
final data = jsonDecode(json) as List;
Map<String, dynamic> map = {};
for (var e in data) {
map.addAll(e);
}
print(map);
//prints
{version: v3.5, setup: true, address: e7d398b, connected: true, active: true, id: ce7143, genuine: true}
If you're using the dio flutter package it returns decoded json, no
need to call for jsonDecode.
I recommend using json code generation if you face large json instead of relying on quicktype generated models.
There's no JSON that isn't parsable with Dart. But you might end up with a data structure that requires careful navigation. Classes make it easier, but there isn't always a class structure for any arbitrary JSON, and maybe that's your point. In that case, you'll have to navigate to the data of interest in an ad-hoc fashion.
Below is my method from .ts file. With this method the keys are displayed but I am unable to fetch the nested JSON data.
generateArr(obj) {
return Object.keys(obj).map((key) => {
console.log(key, obj[key]);
return {key: key, value: obj[key]};
});
}
Below is my HTML code.
<li *ngFor="let ob of books">
<p *ngFor="let objArrEle of generateArr(ob);let i=index">
{{objArrEle.key}}: {{objArrEle.value}}
</p>
</li>
Please tell me the solution.
If you are trying to fetch the nested JSON using interpolation {{}} in HTML, it will display[Object object]. If you want to display the nested data also, you may want to recursively call generateArr(obj) for each nested property. If you are using Angular 7, have a look at KeyValuePipe.
Created a solution for you using stackblitz https://stackblitz.com/edit/angular-nestedjson. you can nest JSON for any level. I'm not so good with CSS, please fell free to change that.
I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John
I'm using simple Angularjs filter where you can filter items in the list with the help of input. I put the code here http://plnkr.co/edit/6vDeOiGNGbblkCBOi8B7?p=preview Filter does work as intended, but if I move data from controller to json and then parse it like that
function($scope, $http) {
$http.get('companies.json').success(function(data) {
$scope.companies = data;
};
Json data renders in the ng-repeat list, but filter search doesn't work anymore. How can I apply filter with json data?
I also added json file I wanted to use to the same plunker.
Your json file is an object instead of an array. So you'd better change it to an array, or
myApp.controller('CompaniesController', ['$http', '$scope',
function($http,$scope) {
$http.get('companies.json').success(function(data) {
var companies = [];
// make the object to an array
for(var companyName in data) {
companies.push(data[companyName]);
}
$scope.companies = companies;
});
}
]);
You can simply turn it to array with toArray filter of angular.filter module.
Usage: object | toArray: addKey[optional]
Note: if addKey set to true,the filter also attaches a new property $key to the value containing the original key that was used in the object we are iterating over to reference the property.
Example:
<input ng-model="model" type="text"/>
<ul>
<li ng-repeat="comp in companies | toArray | filter:model">
{{ comp }}
</li>
</ul>
I am getting json from asana that is an object (data) of several objects. How do I make data an array?
{"data":{"id":5571422294129,"created_at":"2013-05-24T15:31:50.340Z","modified_at":"2013-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
I am trying to put this in a data table using aoColumns. If there is no need to convert "data" to an array please let me know how to use this JSON in datatables without it.
It is not that complicated. You can use DataTables aaData for this. I assume your JSON contains multiple "data":{..}, "data":{..}, "data":{..} ?
Then, consider this as test data :
var data = [
{"data":{"id":1571422294129,"created_at":"2010-05-24T15:31:50.340Z","modified_at":"2010-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":2571422294129,"created_at":"2011-05-24T15:31:50.340Z","modified_at":"2011-05-24T15:32:21.260Z","name":"Project A","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":3571422294129,"created_at":"2012-05-24T15:31:50.340Z","modified_at":"2012-05-24T15:32:21.260Z","name":"Project B","notes":"bla bla","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
];
HTML markup
<table id="test">
<thead>
<tr>
<th>archived</th>
<th>created_at</th>
<th>id</th>
<th>modified_at</th>
<th>name</th>
<th>notes</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
convert JSON to aaData-array :
var aaData = [];
for (var i=0;i<data.length;i++) {
aaData.push([
data[i].data.archived,
data[i].data.created_at,
data[i].data.id,
data[i].data.modified_at,
data[i].data.name,
data[i].data.notes
]);
}
Initialize the table
$('#test').dataTable({
"aaData": aaData
});
result :
I am not sure what you are exactly attempting to do, but...
If you are trying to deserialize the JSON into a data table you want something like this. This will take your JSON and deserialize it to an object, it won't exactly work with a data table but rather custom classes decorated with DataContract and DataMember attributes. But I think it may be a good starting point for you.
Public static T DeSerialize<T>(string strJSON)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJSON));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return (obj);
}
Here is a very useful article regarding serializing JSON. HTH :)
http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx
Regards