Possible Duplicate:
Convert Javascript Array to JSON
I am trying to figure out how to return an array and store it in json variable as string, is that possible? [If not, how can I return all the outputs and store it json?] – If you know what I mean…
//arr = ["a", "b", "c", "d", "ddd"]
//largest = 3
var generateEntryCodes = function(arr, largest) {
var newText = ""
for(var i=0; i < arr.length; i++) {
if (arr[i] == null) {
arr.splice(i, 1);
i--;
}
var counts = arr[i].length != largest ? (parseInt(largest) - parseInt(arr[i].length)) : 0
for (var z=0; z<counts;z++)
newText += "0"
var result = arr[i].splice( 0, 0, newText )
newText = ""
result = [{
"result": result,
"total": result.length
}]
}
return result
}
I am try to output the above code as:
00a
00b
00c
00d
ddd
But as I flash the result json. I only get “ddd”… So I tried adding before the result = [{}] jSON code:
$("textarea").val( $("textarea").val("") + result + "\n")
//outputs:
00a
00b
00c
00d
ddd
How can I get all the outputs from result variable and store it in JSON variable.
Problem: Code only store into JSON the last array.
Generally speaking you can simply construct your JavaScript object and then serialize it to JSON like in the example below:
That should work. Note that you might have to include JSON2.js in case your browser doesn’t support it natively.
//Edit:
That should work: http://jsbin.com/welcome/31083/edit
Here’s the code:
This should return a JavaScript object that looks as follows:
You can then take that result and use
JSON.stringify(...)to convert it into a JSON string.