How to convert JSON Array in JSON Object - json

I have a JSON Array in below format which I want to convert to JSON Object in (key,value) pair.
Since I am new to JSON I don't know how to achieve this.
{
"id": [
"100",
"101",
"102"
],
"Name": [
"ajit",
"amol",
"kiran"
],
"sex": [
"Male",
"Male",
"Male"
]
}
I want to convert above in the format like
[
{
"id": "100",
"Name": "ajit",
"Sex": "Male"
},
{
"id": "101",
"Name": "amol",
"Sex": "Male"
},
{
"id": "102",
"Name": "kiran",
"Sex": "Male"
}
]
Can you guys share your valuable thoughts on how to do this please?
Ajit

Assuming lots of things this works for the example,
var arrayOfObjects = [] ;
/**
* #params Object obj formated like the first one
*/
var i = 0,
arrayOfObjects = [] ;
for( prop in obj ) {
if ( prop instanceof Array ) {
for( i = 0 ; i < obj[prop].length ; ++i ) {
if ( typeof arrayOfObjects[i] !== undefined ) {
arrayOfObjects[i][prop] = obj[prop][i] ;
} else {
var newObj = {} ;
newObj[prop] = obj[prop][i] ;
arrayOfObjects.push(newObj) ;
}
}
}
}

Related

Es6: Create an array of objects from a json

I have a json in the below format.
[
{"id": 1,
"name": "peter" },
{"id": 2,
"name": "john" },
{"id": 3,
"name": "justin" }
.
.
{"id": 500,
"name": "david" },
]
I am trying to create an array in batches of 10 in the below format
[
{
{"id": 1,
"name": "peter" },
.
.
{"id": 10,
"name": "nixon" },
},
{
{"id": 11,
"name": "nancy" },
.
.
{"id": 20,
"name": "underwood" },
}
.
.
]
I tried using reduce and tried for loop to loop through it, but was unsuccessful
Here's a demo.
const str = "abcdefghigklmnopqrstuvwxyz";
let data = [];
for(let i = 0; i < 26; i++){
data.push({id : i, name: str.charAt(i)});
}
let res = data.reduce((acc, d) => {
let groupId = Math.floor(d.id / 10);
acc[groupId] = acc[groupId] || {};
acc[groupId][d.id] = d;
return acc;
}, {});
console.log(Object.values(res));
If you can ensure that id is the same sequence as their position in array, i think simply slice will better.

Put Data in mutlple branch of Array : Json Transformer ,Scala Play

i want to add values to all the arrays in json object.
For eg:
value array [4,2.5,2.5,1.5]
json =
{
"items": [
{
"id": 1,
"name": "one",
"price": {}
},
{
"id": 2,
"name": "two"
},
{
"id": 3,
"name": "three",
"price": {}
},
{
"id": 4,
"name": "four",
"price": {
"value": 1.5
}
}
]
}
i want to transform the above json in
{
"items": [
{
"id": 1,
"name": "one",
"price": {
"value": 4
}
},
{
"id": 2,
"name": "two",
"price": {
"value": 2.5
}
},
{
"id": 3,
"name": "three",
"price": {
"value": 2.5
}
},
{
"id": 4,
"name": "four",
"price": {
"value": 1.5
}
}
]
}
Any suggestions on how do i achieve this. My goal is to put values inside the specific fields of json array. I am using play json library throughout my application. What other options do i have instead of using json transformers.
You may use simple transformation like
val prices = List[Double](4,2.5,2.5,1.5).map(price => Json.obj("price" -> Json.obj("value" -> price)))
val t = (__ \ "items").json.update(
of[List[JsObject]]
.map(_.zip(prices).map(o => _._1 ++ _._2))
.map(JsArray)
)
res5: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"items":[{"id":1,"name":"one","price":{"value":4}},{"id":2,"name":"two","price":{"value":2.5}},{"id":3,"name":"three","price":{"value":2.5}},{"id":4,"name":"four","price":{"value":1.5}}]},/items)
I suggest using classes, but not sure this fits to your project because it's hard to guess how your whole codes look like.
I put new Item manually for simplicity. You can create items using Json library :)
class Price(val value:Double) {
override def toString = s"{value:${value}}"
}
class Item(val id: Int, val name: String, val price: Price) {
def this(id: Int, name: String) {
this(id, name, null)
}
override def toString = s"{id:${id}, name:${name}, price:${price}}"
}
val price = Array(4, 2.5, 2.5, 1.5)
/** You might convert Json data to List[Item] using Json library instead. */
val items: List[Item] = List(
new Item(1, "one"),
new Item(2, "two"),
new Item(3, "three"),
new Item(4, "four", new Price(1.5))
)
val valueMappedItems = items.zipWithIndex.map{case (item, index) =>
if (item.price == null) {
new Item(item.id, item.name, new Price(price(index)))
} else {
item
}
}

underscore.js how to get an element from a JSON object using _.filter

I have the following JSOn object ( Array of elements )
var roles = [
{
"label": "alpha",
"children": [
{"label": "role1","title": "role1","value": "1"},
{"label": "role2","title": "role2","value": "2"}
]
},
{
"label": "beta",
"children": [
{"label": "role3","title": "role3","value": "3"},
{"label": "role4","title": "role4","value": "4"}
]
},
{
"label": "delta",
"children": [
{"label": "role5","title": "role5","value": "5"},
{"label": "role6","title": "role6","value": "6"}
]
}
]
I am trying to get ( and later remove.. ) an element with a specific label
I defined a where object
var where = {key: 'label', value:"alpha"};
and I filter the object :
var filteredRoles = _.filter(roles, function (el) {
return el[where.key] && _.isArray(el[where.key]) &&
_.indexOf(el[where.key], where.value) >= 0;
});
console.log("found "+JSON.stringify(filteredRoles, null, 2));
but I cannot get it : found = []
where am I wrong ?
thanks for feedback
try this
var result = _.filter(roles, function(role) {
return (role[where.key] === where.value) && _.isArray(role['children']);
})
here is a working plunk

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

putting selected values from the JSON

If I do the following on a query :
<cfdump var="#serializeJSON(findglobal)#">
I get the following:
{
"COLUMNS": [
"DELIVERED_PERCENTAGE",
"UNIQUE_PERCENTAGE",
"SPAM_PERCENTAGE",
"DROP_PERCENTAGE",
"REQUEST_PERCENTAGE",
"BOUNCE_PERCENTAGE",
"DEFERRED_PERCENTAGE",
"PROCESSED_PERCENTAGE",
"OPEN_PERCENTAGE",
"BLOCKED_PERCENTAGE"
],
"DATA": [
[
19.54,
6.06,
6.05,
0.63,
21.17,
0.85,
14.83,
20.53,
10.26,
0.19
]
]
}
But I am using Geikoboard which understand only the following format of JSON.
So I would like to have DELIVERED_PERCENTAGE, UNIQUE_PERCENTAGE for the label field below and all the values, like
19.54,6.06 etc for the value field below.
{
"item": [
{
"value": "11234",
"label": "Webmail",
"colour": "FFFF10AA"
},
{
"value": "10736",
"label": "Phone",
"colour": "FFAA0AAA"
},
{
"value": "230",
"label": "Webmail",
"colour": "FF5505AA"
},
{
"value": "280",
"label": "Webmail",
"colour": "FF0000AA"
}
]
}
Do I have to manually generate JSON ?
I think this is what you are looking for. Got it from some site; either Raymon Camden's or Ben Nadel's.
public array function queryToArray( required query qry ) {
var columns = arguments.qry.getColumnNames();
var OutputResult = [];
for( var i = 1; i LTE qry.recordCount; i++ ) {
var obj = {};
for( var k = 1; k LTE arrayLen( columns ); k++ ) {
structInsert( obj, columns[ k ], arguments.qry[ columns[ k ] ][ i ] );
}
arrayAppend(OutputResult, obj );
}
return OutputResult;
}
You would need to do something like this:
<cfset myJSON = queryToArray( myquery ) />
<cfoutput>#serializeJSON( myJSON )#</cfoutput>