I need to convert JSON object string to a JavaScript array.
This my JSON object:
{"2013-01-21":1,"2013-01-22":7}
And I want to have:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['2013-01-21', 1],
['2013-01-22', 7]
]);
How can I achieve this?
This question is related to
javascript
json
This will solve the problem:
const json_data = {"2013-01-21":1,"2013-01-22":7};
const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);
console.log(arr);
Or using Object.entries() method:
console.log(Object.entries(json_data));
In both the cases, output will be:
/* output:
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
If you have a well-formed JSON string, you should be able to do
var as = JSON.parse(jstring);
I do this all the time when transfering arrays through AJAX.
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
See this complete explanation: http://book.mixu.net/node/ch5.html
You can insert object items to an array as this
let obj = {_x000D_
'1st': {_x000D_
name: 'stackoverflow'_x000D_
},_x000D_
'2nd': {_x000D_
name: 'stackexchange'_x000D_
}_x000D_
};_x000D_
_x000D_
let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
_x000D_
console.log(wholeArray);
_x000D_
As simple as this !
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
Suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with (supported in practically all browser versions):
Object.keys(j).map(function(_) { return j[_]; })
or simply:
Object.values(j)
Output:
["1", "2", "3", "4"]
Source: Stackoverflow.com