问题描述:

I have a variable that contains the following JSON string:

{

"0" : "Jun 20, 2012 03:02 PM",

"1" : "Jun 20, 2012 03:26 PM",

"2" : "Jun 21, 2012 01:12 PM",

"3" : "Jun 21, 2012 01:25 PM",

"4" : "Jun 21, 2012 02:42 PM",

"5" : "Jun 21, 2012 02:43 PM",

"6" : "NULL"

}

I wish to convert this JSON to an array in javascript such that

array[0] has "Jun 20, 2012 03:02 PM" array[1] has "Jun 20, 2012 03:26 PM" and so on.

网友答案:

You must parse your JSON string into a javascript object first.

JavaScript

var object = JSON.parse(JSONString);

To polyfill browsers without JSON support: http://bestiejs.github.com/json3/


Then, convert that object to an array:

JavaScript

var arr = [];
for(var i in object) {
    if(object.hasOwnProperty(i)) {
        arr.push(object[i]);
    }
}

jQuery

var arr = $.map(obj,function(value){ return value; });

Fiddle: http://jsfiddle.net/iambriansreed/MD3pF/

Note: Since the original poster did not mention jQuery it is worth mentioning that loading jQuery for only these instances isn't worthwhile, and you would be better off using the pure JavaScript if you aren't already using jQuery.

网友答案:

Alternatively, if you're targeting ES5 and above:

// myObject = { '0': 'a', '1': 'b' };
var myArray = Object.keys(myObject).map(function(key) { return myObject[key]; });
// myArray = [ 'a', 'b' ];
网友答案:

var currentVersion = {/literal} {$displayedVersion} {literal}; var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');

相关阅读:
Top