how to convert a json object into json array - json

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

Related

I think parsing this type of json response is impossible in Dart. How can I convert this json to Dart Class?

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.

Manipulating JSON in Angular

Objective: I am trying to build a website URL by concatenating a variety of variables. I get some from JSON file (audience, country, language) + using constants (baseUrl, tailUrl) + some logic applied to an attribute from JSON file (subdir)
Struggle: I have a service that's getting objects from a JSON and then those objects are being used within the app. My original struggle was to map an object from an array to something else (solved using map and switch/case and that worked fine for an array). However, I am having trouble using the map function with these JSON objects.
So in the .html, I am able to loop through the JSON objects just fine, like so:
`
<table class="table table-striped">
<thead>
<tr>
<th>Audience</th>
<th>Country</th>
<th>Language</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let i of siteUrl; let b =index">
<td>{{i.audience}}</td>
<td>{{i.country}}</td>
<td>{{i.language}}</td>
<td>{{(baseUrl)+(i.audience+"/")+(i.country+"/")+(i.language+"/")+(tailUrl)}}</td>
</tr>
</tbody>
</table>
`
However, when I try to do map the objects from the service, I am unable to do so
`
ngOnInit(){
{
this.baseUrl=baseUrlConst;
this.tailUrl=urlTailConst;
this.siteService=smap.map(item =>{
switch (item.audience) {
case 'ABC':
item.audiencesubdir = 'DEF';
break;
case 'UVW':
item.audiencesubdir = 'XYZ';
}
})
}
}
`
I tried arrays instead of JSON and that works fine, but the objects in the JSON itself don't like this function. My understanding of Angular is novice.

How do we use a JSON result from $http.get in Angular?

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

Create nested JSON structure with Coldfusion

I've been converting CF structs etc to JSON for a while now, and all good. Coldbox in particular makes this really easy.
However, I am currently working with a jQuery Datatable and need to pass it jSON in the format below.
I am starting with an array of objects.
I only want certain properties in each object to go into the final JSON String.
I'm running around in circles and possibly totally overcomplicating converting my data into this format JSON. Can anyone help, or suggest an easy way I might be able to do this..
Also worth mentioning I am building this in coldbox. Coldfusion 9.
{ "aaData": [ [ "Test1", "test#test1", "444444444", "<i class=''icon-pencil icon-large'' data-id=''s1''></i>" ],[ "Test2", "test#test2", "555555555", "<i class=''icon-pencil icon-large'' data-id=''s2''></i>" ],[ "Test3", "test#test3", "666666666", "<i class=''icon-pencil icon-large'' data-id=''s3''></i>" ] ]}
Many Thanks!
======================================================
Here is the code that game we what I needed:
var dataStruct = structNew();
var dataArray = arrayNew(1);
var subsArray = arrayNew(1);
var subs = prc.org.getSubscribers();
for (i=1; i<=arrayLen(subs); i++){
arrayAppend(subsArray,"#subs[i].getName()#");
arrayAppend(subsArray,"#subs[i].getEmail()#");
arrayAppend(subsArray,"#subs[i].getMobile()#");
arrayAppend(subsArray,"<i class='icon-pencil icon-large' data-id='s#subs[i].getID()#'></i>");
arrayAppend(dataArray,subsArray);
arrayClear(subsArray);
};
structInsert(dataStruct,'aaData',dataArray);
event.renderData('json',dataStruct);
OK, so you've got an array which has objects, and the objects contain all the properties which you need to end up in this JSONed array, yeah?
So do this:
create a new array
loop over the array of objects
create a struct
put all the values from each object you need to go into the JSON; be mindful to use associative array notation when setting the keys, to perserve the case of the keys
append the struct to the new array
/loop
serializeJson the new array
I don't think there's any simpler way of doing it.

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types