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?
Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
JSON text/object can be converted into Javascript object using the function JSON. parse(). If we pass a invalid JSON text to the function JSON. parse(), it will generate error (no output is displayed when using in tag of HTML).
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.
var json_data = {"2013-01-21":1,"2013-01-22":7}; var result = []; for(var i in json_data) result.push([i, json_data [i]]); var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices'); data.addRows(result);
http://jsfiddle.net/MV5rj/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With