View Full Version : Easy way to convert a Javascript array to a JSON string?
harjanto
03-27-2008, 12:03 PM
Is there an easy way to convert a Javascript array to a JSON string equivalent of the array?
Assume the array is comprised of strings
Thanks for the help
mic2100
03-27-2008, 01:53 PM
go check this page out it will show you some examples of using JSON objects in JavaScript.
http://www.json.org/js.html
What do you mean by JSON string? A string is a string. Period. To convert an array to a string is enough to use the join() method
rnd me
04-06-2008, 11:06 AM
he means a string that evals into an array.
[1,2,3,false,"hello"].toSource() works perfectly in firefox...
use .toJSONString() in the library floating around the page referred to above for cross browser compat.
kaitana
02-01-2012, 05:44 AM
I searched a lot for this .. could not find it.
so I would try this:
checkIfMultiDimentional = function(arr)
{
for(var item in arr)
{
if(typeof(arr[item]) == 'object') { return true; }
}
return false;
}
myJsonify = function(thing, level)
{
var jsonString = "";
if(!level) { level = 0; }
var start;
if(typeof(thing) == 'object') {
if(checkIfMultiDimentional(thing))
{
start = 0;
for(var item in thing)
{
var value = thing[item];
if(start > 0) { jsonString += ','; }
if(value.substring) { jsonString += item+":"+value; }
else { jsonString += "\""+item+"\":{"+myJsonify(value, level+1)+"}"; }
start++;
}
}
else
{
start = 0;
for(var item in thing)
{
if(start > 0){ jsonString +=','; }
jsonString += "\""+item+"\":"+thing[item];
start++;
}
return jsonString;
}
}
else { jsonString = thing; }
return jsonString;
}
hope this helps everyone :)
kaitana
02-01-2012, 06:07 AM
Usage
var jsonstr = "{"+myJsonify( multiDimentionalArray )+"}";
//alert(jsonstr);
var facUrl = "/factoryajax?json="+jsonstr;
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.