Raj Nepali Raj Nepali - 5 months ago 10
JSON Question

How to convert a JSON dictionary to a list of values?

I have following JSON string:

{"Local People":{"label":"Local People","data":1},"Student":{"label":"Student","data":1}}


I want to convert it to the following:

[{
"label" : "Student",
"data" : 1
},
{
"label" : "Student",
"data" : 1
}]


I have tried it many times but I've been unsuccessful. Please help!

Answer

After you have parsed the string with JSON.parse, you could take the keys of the object and iterate over the properties for a new array with the items.

var JSONstring='{ "Local People": { "label": "Local People", "data": 1 }, "Student": { "label": "Student", "data": 1 } }'
    object = JSON.parse(JSONstring),
    array = Object.keys(object).map(function(k) {
        return object[k];
    });

console.log(array);