Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Cheating -> string.split(',') –  adeneo Jan 25 '13 at 18:53
    
@adeneo he wants array in array, with your method it will be just one array –  salexch Jan 25 '13 at 18:55

3 Answers 3

up vote 13 down vote accepted
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/

share|improve this answer
    
Thank for your response , –  user1960311 Jan 25 '13 at 19:00
    
@user1960311 you welcome –  salexch Jan 25 '13 at 19:02
    
I would like something like this: 2013-01-21 ==> 1 2013-01-22 ==> 7 (like a hashtable) –  user1960311 Jan 25 '13 at 19:04
    
@user1960311 That's what you have now –  Ian Jan 25 '13 at 19:07

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.

share|improve this answer
1  
+1 for JSON.parse(). At this point it has broad browser support: caniuse.com/json –  siliconrockstar Dec 19 '13 at 23:32
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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.