Чтобы превратить строковое представление в массив, нужно воспользоваться функцией eval():
eval("(" + json_string + ")");
А чтобы превратить массив в строковое представление:
/**
* Converts the given data structure to a JSON string.
* Argument: arr - The data structure that must be converted to JSON
* Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
* var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
* [url]http://www.openjs.com/scripts/data/json_encode.php[/url]
*/
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
for(var key in arr) {
var value = arr[key];
if(typeof value == "object") { //Custom handling for arrays
if(is_list) parts.push(array2json(value)); /* :RECURSION: */
else parts[key] = array2json(value); /* :RECURSION: */
} else {
var str = "";
if(!is_list) str = '"' + key + '":';
//Custom handling for multiple data types
if(typeof value == "number") str += value; //Numbers
else if(value === false) str += 'false'; //The booleans
else if(value === true) str += 'true';
else str += '"' + value + '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
parts.push(str);
}
}
var json = parts.join(",");
if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}
Пример:
var json_string = array2json(['e', {pluribus: 'unum'}]);//Returns '["e", {"pluribus": "unum"}]'
var data = {
"success":"Sweet",
"failure":false,
"empty_array":[],
"numbers":[1,2,3],
"info":{
"name":"Binny",
"site":"http:\/\/www.openjs.com\/"
}
};
var json = array2json(data); // Returns {"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}}