I am having a problem while converting an array into Json object. I have an array which contain json objects/objects, when i convert that array into Json object it combine/concatenate array data rahter than making json array. lets suppose array have two json objects. when i convert it into json object using
var jsondata = JSON.stringify(array);
var jsn = JSON.parse(jsondata);
here is my code:
var array = new Array();
function addBatch(){
var data = $.toJSON($('#risk').serializeArray());
//data = [{"name":"user","value":"INCRE"},{"name":"period","value":"100"},{"name":"hori","value":"12"},{"name":"conf","value":"32"}]
var jsonData = JSON.stringify(data);
var json=JSON.parse(jsonData);
console.log('After Converting Json');
//store data in array
array.push(json);
}
// function that convert array into json:
function saveBatch(){
var jsonData = JSON.stringify(array);
json = JSON.parse(jsonData);
console.log("Batch: "+json);
}
it give me following output:
[{"name":"user","value":"HIST"},{"name":"period","value":"12"},{"name":"hori","value":"32"},{"name":"conf","value":"12"}],[{"name":"user1","value":"INCRE"},{"name":"period","value":"12"},{"name":"hori","value":"32"},{"name":"conf","value":"12"}]
it should be like this:
[
[
{"name":"obj1"},{"value":"data"}
],
[
{"name":"obj2"},{"value":"data2"}
]
]
dont know why this is happening. I search on Google as well but i didn't find any way except
var jsondata = JSON.stringify(array);
var jsn = JSON.parse(jsondata);
What you have doesn't make alot of sense. Are you sure you don't want an array of objects?
var array = new Array();
function addBatch() {
// Gets data. Returns an array of objects in format [{name: "", value: ""}, ...]
var data = $.toJSON($('#risk').serializeArray());
// Extend the `array` with new objects.
array.concat(data);
}
// function that convert array into json:
function saveBatch() {
// Convert the array of objects to JSON string.
var jsonData = JSON.stringify(array);
console.log(jsonData);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.