0

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
}
]
3
  • Your for loop will iterate over outer values of Json. You need to another iterate inside data object. Also once you reach desired key, you will need to pull size from that object. Commented Nov 8, 2016 at 0:03
  • 3
    Would be great if you could post valid JSON Commented Nov 8, 2016 at 0:04
  • @adeneo,thanks for your reply. i've updated the JSON , Commented Nov 8, 2016 at 2:38

1 Answer 1

1
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 + ';';
    }); //update
  }
}); //update

if (finalStr.length > 0) { // at least one entry was added
  finalStr.slice(0, -1);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.