Node.js - JSON object manipulation - json

I have a problem converting my JSON to desired format. I have something like this:
{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}
and I would like to get:
[
["one","5","10"],
["two","6","11"]
]
Any help appreciated...

Assuming that your JSON is:
{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}
and your desired JSON is:
[
["one","5","10"],
["two","6","11"]
]
Then you can iterate over the keys of your object and add the values of the elements to another hash with shorter keys, and then convert that new hash to an array of arrays.
Example
let json1 = `{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}`;
function convert(j) {
let o = JSON.parse(j);
let h = {};
for (let k of Object.keys(o)) {
let n = k.split(':')[0];
if (!h[n]) h[n] = [];
h[n].push(o[k]);
}
let a = Object.keys(h).map(k => [k].concat(h[k]));
return JSON.stringify(a);
}
let json2 = convert(json1);
console.log('json1:', json1);
console.log('json2:', json2);
See: DEMO
Example for Node 0.10
This should work on Node v0.10.x:
var json1 = '{\n' +
' "one:apple": "5",\n' +
' "one:orange": "10",\n' +
' "two:apple": "6",\n' +
' "two:orange": "11"\n' +
'}';
function convert(j) {
var o = JSON.parse(j);
var h = {};
for (var k in o) {
if (o.hasOwnProperty(k)) {
var n = k.split(':')[0];
if (!h[n]) h[n] = [];
h[n].push(o[k]);
}
}
var a = Object.keys(h).map(function (k) {
return [k].concat(h[k]);
});
return JSON.stringify(a);
}
var json2 = convert(json1);
console.log('json1:', json1);
console.log('json2:', json2);
See: DEMO

Related

Get keys of json data of certain level

I got parsed data object. The data is retuned by backend as JSON and has been parsed as data object in react-native client.
{
"level1-key1": "value1",
"level1-key2": "value2",
"level1-key3": "value3",
"level1-key4":{
"level2-k1": "val1",
"level2-k2": {
"level3-k1": "v1",
"level3-k2": "v2",
"level3-k3": "v3"
}
}
}
I would like to get different level keys as an array of strings, i.e. I want to get level 2 keys, which are ["level2-k1", "level2-k2"].
I want to get level 3 keys, which are
["level3-k1", "level3-k2", "level3-k3"]
How achieve it?
I think it should solve your problem
const data = {
'level1-key1': 'value1',
'level1-key2': 'value2',
'level1-key3': 'value3',
'level1-key4': {
'level2-k1': 'val1',
'level2-k2': {
'level3-k1': 'v1',
'level3-k2': 'v2',
'level3-k3': 'v3',
},
},
};
const isObject = (v) => typeof v === 'object' && v != null;
const getAllKeysByLevel = (data, level) => {
let levelObjects = [data];
for (let i = 0; i < level; i += 1) {
levelObjects = levelObjects.flatMap((item) =>
isObject(item) ? Object.values(item) : [],
);
}
return levelObjects.flatMap((item) =>
isObject(item) ? Object.keys(item) : [],
);
};
const level1 = getAllKeysByLevel(data, 0);
const level2 = getAllKeysByLevel(data, 1);
const level3 = getAllKeysByLevel(data, 2);
console.log(' --- xdebug ', {
level1,
level2,
level3,
});
/*
--- xdebug {
level1: [ 'level1-key1', 'level1-key2', 'level1-key3', 'level1-key4' ],
level2: [ 'level2-k1', 'level2-k2' ],
level3: [ 'level3-k1', 'level3-k2', 'level3-k3' ]
}
*/
This should do the work, finding out the leaf nodes and check if it is an object and repeat it till the end.
const data = {
"level1-key1": "value1",
"level1-key2": "value2",
"level1-key3": "value3",
"level1-key4":{
"level2-k1": "val1",
"level2-k2": {
"level3-k1": "v1",
"level3-k2": "v2",
"level3-k3": "v3"
}
}
}
function findLevels(data){
let counter = 1;
let final = {};
getKeys(data)
function getKeys(obj){
let k = Object.keys(obj);
final[counter] = k;
// scan if there is any object
for(let i = 0; i < k.length; i++){
if(typeof obj[k[i]] === "object"){
counter += 1;
getKeys(obj[k[i]])
}
}
}
return final;
}
const result = findLevels(data);
console.log(result)

Flutter get Object property Name

I passed the following object:
var myVar = { typeA: { option1: "one", option2: "two" } }
I want to be able to pull out the key typeA from the above structure.
This value can change each time so next time it could be typeB.
So I would like to know if there is any way to do that
I was able to solve using 'keys'
for a json example like this:
{
"1-0001": {
"name": "red",
"hex": "FF0000"
},
"1-0002": {
"name": "blue",
"hex": "0000FF"
},
"1-0003": {
"name": "green",
"hex": "008000"
}
}
I was able to use
Map<String, dynamic> decoded = json.decode(jsonString);
for (var colour in decoded.keys) {
print(colour); // prints 1-0001
print(decoded[colour]['name']); // prints red
print(decoded[colour]['hex']); // prints FF0000
}
To get all filenames you can use:
var data = ...
var filenames = [];
for(var i = 0; i < data.length; i++) {
var item = data[0]['files'];
var key = item.keys.first;
var filename = item[key]['filename'];
filenames.add(filename);
}
print(filenames);
You need to define a data type.
It is basically a map of (key value-pair) where key is changed as stated in question typeA or typeB
This Object has 2 properties option1 and option2 which is also strings.
Here is the sample code to construct model and how to use it
import 'package:TestDart/TestDart.dart' as TestDart;
main(List<String> arguments) {
var map = new Map<String, MyObject>();
map['typeA'] = new MyObject("one", "two");
map['typeB'] = new MyObject("one", "two");
print(map['typeA'].toString());
print(map['typeA'].toString());
}
class MyObject {
String _option1;
String _option2;
MyObject(this._option1, this._option2);
String get option2 => _option2;
String get option1 => _option1;
#override
String toString() {
return 'MyObject{option1: $_option1, option2: $_option2}';
}
}
Relevant answer
map.forEach((key, value) {
print("Key : ${key} value ${value}");
});

How do I format my JSON?

I have JSON of this format
[
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
]
I want my JSON into
{
"universityID":"454",
"grade":"88",
"date":"15-Jan-2016",
"address":"Washington"
}
You just iterate on your array and stuff each attribute into a new object as they come:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
output[attr.name] = attr.value;
});
console.log(output);
EDIT: If universityID needs to be an array:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
if (attr.name == "universityID") {
if (!(attr.name in output)) output[attr.name] = [];
output[attr.name].push(attr.value);
} else {
output[attr.name] = attr.value;
}
});
console.log(output);

Json object merge with unqiue id

I have multiple json Objects
json1 = [
{'category_id':1,'name':'test1' },
{'category_id':1,'name':'test2' },
{'category_id':1,'name':'test3' },
{'category_id':2,'name':'test2' },
{'category_id':3,'name':'test1' }
];
json2 = [{'category_id':1,'type':'test1'}];
json3 = [
{'category_id':1,'color':'black'},
{'category_id':2,'color':'black'},
{'category_id':3,'color':'white'}
];
I am expecting output like this
final = [
{'category_id':1,'name':'test1','type':'test`','color':'black' },
{'category_id':1,'name':'test2','type':'test`','color':'black' },
{'category_id':1,'name':'test3','type':'test`','color':'black' },
{'category_id':2,'name':'test2','color':'black' },
{'category_id':3,'name':'test1','color':'white' }
];
As i have long json object. Looping is good idea or not ? Does there is any inbuilt function for doing the same.
Using underscore you can achieve it via:
Demo Fiddle
var jsons = [json1, json2, json3];
var final = {};
// merge all data
_.each(jsons, function (jsonArr) {
_.each(jsonArr, function (json) {
final[json.category_id] = _.extend({}, final[json.category_id], json);
});
});
// map it back onto json1
var finalArr = _.map(json1, function (json) {
return final[json.category_id];
});
console.log(finalArr);
Final value of finalArr:
Here is how you can do the same in plain javascript. :)
var final = {};
var jsons = [json1, json2, json3];
for(var i=0;i<jsons.length;i++){
final[i]=jsons[i];
}
Fiddle
EDIT:
Well, you will have to do it programmatically!

mootools nested object filtering

I have a JSON string:
var data = {"categories":
[
{"id":1,"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":[]},
{"id":2,"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":
[
{"id":6,"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":[]},
{"id":7,"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":[]}
]
},
{"id":3,"parent":0,"name":"Category C","description":"Category description","products":"4","subcategories":
[
{"id":8,"parent":3,"name":"Subcategory H","description":"Category description","products":"8","subcategories":[]}
]
},
{"id":4,"parent":0,"name":"Category D","description":"Category description","products":"45","subcategories":
[
{"id":9,"parent":4,"name":"Subcategory I","description":"Category description","products":"2","subcategories":
[
{"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
]
}
]
},{"id":5,"parent":0,"name":"Category E","description":"Category description","products":"89","subcategories":[]}
]
};
How can access to the data by id?
For example I need to get this sub_object with id = 10:
var requested = request(data, 10);
function request (data, id) {
var output = {};
...code
output = {"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
return output;
}
Basically you can do it by a simple recursion: http://jsfiddle.net/99UYU/
var data = {"categories":
[
{"id":1,"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":[]},
{"id":2,"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":
[
{"id":6,"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":[]},
{"id":7,"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":[]}
]
},
{"id":3,"parent":0,"name":"Category C","description":"Category description","products":"4","subcategories":
[
{"id":8,"parent":3,"name":"Subcategory H","description":"Category description","products":"8","subcategories":[]}
]
},
{"id":4,"parent":0,"name":"Category D","description":"Category description","products":"45","subcategories":
[
{"id":9,"parent":4,"name":"Subcategory I","description":"Category description","products":"2","subcategories":
[
{"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
]
}
]
},{"id":5,"parent":0,"name":"Category E","description":"Category description","products":"89","subcategories":[]}
]
};
function recurseArr(arr,id){
for(var i=0;i<arr.length;i++){
var item = arr[i];
if(item.id == id){
return item;
}
var subcategories = item.subcategories;
var ret_val = recurseArr(subcategories,id);
if(ret_val){
return ret_val;
}
}
return null;
}
console.log(recurseArr(data.categories,10));
But you can save your data more usefully because you are using id anyhow - so instead array use objects(map):
var data = {"categories":
{
"1":{"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":{}},
"2":{"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":{
"6":{"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":{}},
"7":{"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":{}}
}
}
}
};
then you can access your data more easily.