Jakk Jakk - 1 month ago 15
Javascript Question

JSON: key value concatenation in javascript

I'm trying to parse json object to get the key and value concatenated to a variable.
My desired output from the given json is:

"/" - 7.84 GiB; "/opt" - 4.86 GiB; "/usr" - 4.80 GiB


Using my snippet i can get objects but struggling to get the name and value in desired format. Please assist.

for (i = 0; i < obj.length; i++)
{
if ( obj[i].name === 'mountpoints')
{
js_mountpoints = obj[i].value;
break;
}
js_mountpoints = 'NA';
}


My JSON input:

[{
"name" : "pe_build",
"value" : "2016.2.1"
},
{
"name" : "kernel",
"value" : "Linux"
}, {
"name" : "blockdevices",
"value" : "sda,sdb,sr0"
},
{
"name" : "mountpoints",
"value" : {
"\/boot\/efi" : {
"size_bytes" : 261861376,
"size" : "249.73 MiB",
"capacity" : "0%"
},
"\/opt" : {
"size_bytes" : 2086666240,
"size" : "1.94 GiB",
"capacity" : "1.64%"
},
"\/boot" : {
"size_bytes" : 258650112,
"size" : "246.67 MiB",
"capacity" : "74.28%"
},
"\/var" : {
"size_bytes" : 10475274240,
"size" : "9.76 GiB",
"filesystem" : "xfs",
"capacity" : "4.01%"
}
}
}, {
"name" : "uptime_seconds",
"value" : 244181
}, {
"name" : "memoryfree",
"value" : "6.66 GiB"
}, {
"name" : "memoryfree_mb",
"value" : 6816.91796875
}
]

Answer
finalStr = ''
Object.keys(obj).forEach(function(key) {
  if (obj[key].name === 'mountpoints') { // only get sizes for mountpoints
    var value = obj[key].value;
    Object.keys(value).forEach(function(name) { // add all sizes to string
      finalStr += '"' + name + '" - ' + value[name].size + ';';
    }
  }
}

if (finalStr.length > 0) { // at least one entry was added
  finalStr.slice(0, -1);
}