Normalise JSON object key names - javascript

I am wanting to write a function to turn a JSON object's keys into more appropriate names. As you can see by the JSON object below, the keys are 1 letter and are not very readable or useful for anyone. Therefore I would like to loop through the object (or something similar) and rename all the keys, and then return this JSON.
{
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2,
"st": "2017-04-27T15:01:29Z",
"o": 0,
"r": true,
"u": "2017-04-27T15:01:29Z",
"t": "p",
"i": "371871",
"z": 1493305289586
}

You can reduce object keys to new object, e.g.:
const obj = {
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2,
"st": "2017-04-27T15:01:29Z",
"o": 0,
"r": true,
"u": "2017-04-27T15:01:29Z",
"t": "p",
"i": "371871",
"z": 1493305289586
}
// [key] -> [normalized name] mapping
const names = {
"e": "e-name",
"pp": "pp-name",
"c": "c-name",
"x": "x-name",
"st": "st-name",
"o": "o-name",
"r": "r-name",
"u": "u-name",
"t": "t-name",
"i": "i-name",
"z": "z-name"
}
const renamedProps = Object.keys(obj).reduce((renamed, key) => {
renamed[names[key]] = obj[key];
return renamed;
}, {});

var obj = {
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2
},
names = ["e_new-name", "pp_new-name", "c_new-name", "x_new-name"],
updated = {},
keys = Object.keys(obj);
for (i = 0; i < keys.length; i++) {
updated[names[i]] = obj[keys[i]];
}
console.log(JSON.stringify(updated));
// will print
// {"e_new-name":"56049","pp_new-name":"371861","c_new-name":"GAME","x_new-name":2}
jsfiddle

Related

Object Child Key Path

I want to iterate through nested Object and I want to store the all the child keys path as separate array
{
"A": {
"C": {
"G": {}
}
},
"B": {
"D": {
"G": {}
},
"E": {
"H": {}
},
"F": {
"I": {
"H": {}
},
"J": {}
}
}
}
I need Array in below format.
A,C,G
B,D,G
B,E,H
B,F,J
B,F,I,H
You can use recursion with Object.entries to get the values.
Here is an example.
const data = {
"A": {
"C": {
"G": {}
}
},
"B": {
"D": {
"G": {}
},
"E": {
"H": {}
},
"F": {
"I": {
"H": {}
},
"J": {}
}
}
};
const result = []
function getPaths(data,path=''){
const list = Object.entries(data)
if(!list.length){
result.push(path)
return
}
list.forEach(([key,value])=>getPaths(value,path ? path+','+key : key))
}
getPaths(data)
console.log(result)

Iterate through nested JSON object array and store as key-value pair

I have to iterate through this JSON:
{
"data": 321563,
"group": [
{
"added": 42421,
"normal": {
"x": 39,
"y": "0.1300",
"b": "0.4326",
"c": "0.0552",
"f": 166833
},
"j": "240313",
"b": "0.2251",
"a": "dda",
"b": "0.101",
"a": 922,
"f": {
"c": 39,
"d": "0.263",
"a": "2.8955",
"h": "0.3211",
"d": 274
},
"a": false,
"k": 5,
"w": "0.072",
"d": "0.045",
"e": 3
},
I only want the j and k stored like a key value pair e.g. "j":k
I need to loop all of it, and store it to a file.
You can use a map to get a new array of items, this will not affect the old array.
const data = {
"game_count": 8750,
"sets": [
{
"appid": "221540",
"true_count": 9,
"bgs_avg": "0.10",
// Other data here
},
{
"appid": "123456",
"true_count": 9,
"bgs_avg": "0.20",
// Other data here
}
]
}
// Use "data.sets = data.sets.map(...)" to replace the data
// The following will only assign to a new variable
const newArray = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} })
console.log(newArray)
We can also take the data and assign it directly back to the original overwriting it just by using data.sets = data.sets.map(...) as seen here:
const data = {
"game_count": 8750,
"sets": [
{
"appid": "221540",
"true_count": 9,
"bgs_avg": "0.10",
// Other data here
},
{
"appid": "123456",
"true_count": 9,
"bgs_avg": "0.20",
// Other data here
}
]
}
data.sets = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} })
console.log(data)
In simple javascript this should work -
let newObj = {}
for(let i=0; i<obj.group.length; i++){
newObj[obj.group[i].j] = obj.group[i].k
}
Where 'obj' is your object
newObj will be you new Object which will contain all the key value pair

How to iterate over a json object list?

i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.
var voltot = 0;
$.each(json,function(k,v){
voltot = v.B += voltot ;
//console.log(v.B);
});
console.log(voltot);
HERE IS MY FULL JSON OBJECT.
var json=
[
{
"a": "OOCBER",
"b": "OOCL BERLIN",
"c": "CHINA",
"d": "GREAT BRITAIN",
"e": "*PI",
"f": "NGB",
"g": "CN",
"i": "GB",
"n": 9,
"o": 6,
"p": "2015-09-14",
"q": "2015-09-14",
"s": 4,
"u": "40HC",
"v": "TRLU7564566",
"w": "CN0794909",
"x": "LEIGH",
"y": "NINGBO",
"z": 395,
"B": 68.8,
"C": 7987.5,
},
{
"a": "OOCBER",
"b": "OOCL BERLIN",
"c": "CHINA",
"d": "GREAT BRITAIN",
"e": "*PI",
"f": "NGB",
"g": "CN",
"i": "GB",
"n": 9,
"o": 6,
"p": "2015-09-14",
"q": "2015-09-14",
"s": 4,
"u": "40HC",
"v": "TCLU8306124",
"w": "CN0786008",
"x": "OXFORDSHIRE",
"y": "NINGBO",
"z": 412,
"B": 68,
"C": 8790.5,
}
]
i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.
var voltot = 0;
$.each(json,function(k,v){
voltot = v.B += voltot ;
//console.log(v.B);
});
console.log(voltot);
This is wrong
voltot = v.B += voltot ;
Make like this
voltot += v.B;
Or
voltot = v.B + voltot ;
The preferred method to obtain an unique value from an array is the Array.prototype.reduce method, which takes a callback function and a starting value (it reduces an array to a single value). You could use it this way :
json.reduce(function(total, current) { return typeof current.B === "number" ? total + current.B : total; }, 0);
Here is a JSFiddle.
Here's JSFiddle. I just shrunk json and post. Try with full json array
var json=
[
{
"z": 395,
"B": 68,
"C": 7987.5,
},
{
"z": 395,
"B": 68,
"C": 7987.5,
}
];
var voltot = 0;
$.each(json,function(k,v){
voltot += v.B;
});
console.log(voltot);
The operator += is incorrect. #RiccardoC answer was correct.
Also, you don't need to use jquery to sum the values. You could simply do the following
var voltot=0;
json.forEach(function(element) {voltot+=element.B})
The forEach function will run a callback for each element of your array

JSON.parse() works from console but not from function/code

Why parsing string into JSON (previously created with JSON.stringify()) works from console but from function it gives enigmatic error?
console.log(output); // in console i copy it into JSON.parse() and it works
output = JSON.parse(output); // Uncaught SyntaxError: Unexpected token index:1
My JSON:
{"type":"a","items":[{"id":"767758","id1":"1384882","id2":"1413749","c":"rgba(0, 100, 0, 5)","ls":"dashed","type":"l","d":{"t":"r","type":"1","hist":true},"w":5,"off":0},{"id":"6493942","id1":"1384882","id2":"5467332","c":"rgba(105, 105, 105, 5)","ls":"1","type":"l","d":{"t":"r","type":"h","hist":false},"w":5,"off":0},{"id":"1384882","id":"6c409d02-d937-11e4-a891-53b449010d08","d":{"t":"p","age":41,"xxx":5},"type":"n","t":"123","u":"p.png","g":[{"c":"rgb(255, 255, 255)","p":"ne","t":"5","fc":"rgb(0, 0, 0 )","w":false}],"x":-20.876105573962775,"y":41.26542299248838},{"id":"1413749","id":"e7e70a00-d3e4-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"zxc","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"42","fc":"rgb(0, 0, 0)","w":5},{"c":"rgb(0, 0, 255)","p":"nw","fc":"rgb(0, 0, 0)"}],"x":149.06285284387724,"y":5.308329729351229},{"id":"5467332","id":"8f0f5c30-d3d9-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"asd","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"","fc":"rgb(0, 0, 0)","w":false},{"p":"nw","fc":"rgb(0, 0, 0)"}],"x":-164.24347467678655,"y":-32.64876353378594}],"combos":{"iop":[],"dfg":[]},"jk":{"width":966,"height":890,"zoom":5,"offsetX":905,"offsetY":744}}
My code, there's something missing as others gave working JSfiddles:
var memory = '';
$buttonSave.click(function (event) {
if (helpers.isNUE(chart)) { return; }
var data = chart.serialize();
data = JSON.stringify(data).split(''); // string to array
data.forEach(function (datum) { // foreach character
memory += datum.charCodeAt(0).toString(2) + '2'; // get binary charcode, add padding "2"
});
console.info('memory saved: ' + memory);
event.preventDefault();
return false;
});
$buttonLoad.click(function (event) {
var data = memory.split('2'), // get binary code for each character
output = '',
serializedChart = {};
data.forEach(function (datum) {
output += String.fromCharCode(parseInt(datum, 2)); // read binary charcode and get character from it
});
console.warn('load done:');
try {
serializedChart = JSON.parse(output);
} catch (e) {
console.warn(e);
}
});
You are missing a final } from your json string. use this:
{
"type": "a",
"items": [
{
"id": "767758",
"id1": "1384882",
"id2": "1413749",
"c": "rgba(0, 100, 0, 5)",
"ls": "dashed",
"type": "l",
"d": {
"t": "r",
"type": "1",
"hist": true
},
"w": 5,
"off": 0
},
{
"id": "6493942",
"id1": "1384882",
"id2": "5467332",
"c": "rgba(105, 105, 105, 5)",
"ls": "1",
"type": "l",
"d": {
"t": "r",
"type": "h",
"hist": false
},
"w": 5,
"off": 0
},
{
"id": "6c409d02-d937-11e4-a891-53b449010d08",
"d": {
"t": "p",
"age": 41,
"xxx": 5
},
"type": "n",
"t": "123",
"u": "p.png",
"g": [
{
"c": "rgb(255, 255, 255)",
"p": "ne",
"t": "5",
"fc": "rgb(0, 0, 0 )",
"w": false
}
],
"x": -20.876105573962775,
"y": 41.26542299248838
},
{
"id": "e7e70a00-d3e4-11e4-b3ef-53b449010d08",
"d": {
"t": "c",
"active": true,
"r": 47
},
"type": "n",
"t": "zxc",
"u": "p.png",
"g": [
{
"c": "#ccff99",
"p": "ne",
"t": "42",
"fc": "rgb(0, 0, 0)",
"w": 5
},
{
"c": "rgb(0, 0, 255)",
"p": "nw",
"fc": "rgb(0, 0, 0)"
}
],
"x": 149.06285284387724,
"y": 5.308329729351229
},
{
"id": "8f0f5c30-d3d9-11e4-b3ef-53b449010d08",
"d": {
"t": "c",
"active": true,
"r": 47
},
"type": "n",
"t": "asd",
"u": "p.png",
"g": [
{
"c": "#ccff99",
"p": "ne",
"t": "",
"fc": "rgb(0, 0, 0)",
"w": false
},
{
"p": "nw",
"fc": "rgb(0, 0, 0)"
}
],
"x": -164.24347467678655,
"y": -32.64876353378594
}
],
"combos": {
"iop": [],
"dfg": []
},
"jk": {
"width": 966,
"height": 890,
"zoom": 5,
"offsetX": 905,
"offsetY": 744
}
}
Is output already parsed? If so, it looks like you're trying to parse output twice, if the output is already a JSON value, you do not need to parse it again.
You're missing an } at the end of your JSON. If you add that it should work.
{"type":"a","items":[{"id":"767758","id1":"1384882","id2":"1413749","c":"rgba(0, 100, 0, 5)","ls":"dashed","type":"l","d":{"t":"r","type":"1","hist":true},"w":5,"off":0},{"id":"6493942","id1":"1384882","id2":"5467332","c":"rgba(105, 105, 105, 5)","ls":"1","type":"l","d":{"t":"r","type":"h","hist":false},"w":5,"off":0},{"id":"1384882","id":"6c409d02-d937-11e4-a891-53b449010d08","d":{"t":"p","age":41,"xxx":5},"type":"n","t":"123","u":"p.png","g":[{"c":"rgb(255, 255, 255)","p":"ne","t":"5","fc":"rgb(0, 0, 0 )","w":false}],"x":-20.876105573962775,"y":41.26542299248838},{"id":"1413749","id":"e7e70a00-d3e4-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"zxc","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"42","fc":"rgb(0, 0, 0)","w":5},{"c":"rgb(0, 0, 255)","p":"nw","fc":"rgb(0, 0, 0)"}],"x":149.06285284387724,"y":5.308329729351229},{"id":"5467332","id":"8f0f5c30-d3d9-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"asd","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"","fc":"rgb(0, 0, 0)","w":false},{"p":"nw","fc":"rgb(0, 0, 0)"}],"x":-164.24347467678655,"y":-32.64876353378594}],"combos":{"iop":[],"dfg":[]},"jk":{"width":966,"height":890,"zoom":5,"offsetX":905,"offsetY":744}}
What is typeof output? For parse() to work, it must be string but the dump in your question looks like it would return object. object means that the JSON has already been parsed and it's a JavaScript object.
So this would work:
var output = '{"type":"a","items":[{...}]}';
output = JSON.parse(output);
while this won't:
var output = {
"type":"a",
"items":[{...}]
};
output = JSON.parse(output);

Generating dictionaries and lists in JavaScript after a JSON

I'm receiving a JSON in this format:
{
"0": {
"a": 0.0,
"b": 1.0,
"G": 6.0,
"w": 0.0,
"F": -1.0
},
"1": {
"a": 0.0,
"b": 0.1429004669189453,
"G": 0.000301361083984375,
"w": 0.1429004669189453,
"F": -1.0
},
"2": {
"a": 0.0,
"b": 0.1429004669189453,
"G": 0.000301361083984375,
"w": 0.1429004669189453,
"F": -1.0
},
"3": {
"a": 0.0,
"b": 0.1429004669189453,
"G": 0.000301361083984375,
"w": 0.1429004669189453,
"F": -1.0
....
Let's say I call that a json variable. I'm trying to turn it into something like:
[
{"key": "series1",
values: [
[`json`["1"]["a"],`json`["1"]["F"]],[`json`["1"]["b"],`json`["1"]["G"]]
]
},
{"key": "series2",
values: [
[`json`["2"]["a"],`json`["2"]["F"]],[`json`["2"]["b"],`json`["2"]["G"]]
]
},
{"key": "series3",
values: [
[`json`["3"]["a"],`json`["3"]["F"]],[`json`["3"]["b"],`json`["3"]["G"]]
]
},
....
]
I tried this JavaScript for accomplishing it but got lost :S
var data = function myData(json) {
series = {}
for (iteracion in json) {
series.push({
key: iteracion, values: [[x: iteracion['a'], y: iteracion['F']],[x: iteracion['b'], y: iteracion['G']]]
})
}
return series
A solution to your problem is:
var result = [];
for (var series in json) {
result.push({
key : 'series' + series,
values : [
json[series].a,
json[series].F,
json[series].b,
json[series].G,
]
});
}
If you don't really need an array of objects that contain a key and a value, i organized your information slightly better:
var result = {};
for (var series in json) {
result['series' + series] = [
json[series].a,
json[series].F,
json[series].b,
json[series].G,
];
}
This results in something like this:
{
series0 : [ 0, -1, 1, 6 ],
series1 : [ 0, -1, 0.14, 0.0003],
...
}

Categories