Sandeep sandy Sandeep sandy - 1 month ago 6x
Javascript Question

How to prepare a parsable json array of object?

var cdrType = $('.switchSelect').val();
console.log(cdrDisplayFields);//[Object, Object, Object, Object, Object, Object]
var a = '{"cdrColumnFields":'+cdrDisplayFields[0]+'}';
console.log(a); //{"cdrColumnFields":[object Object]}
console.log(cdrDisplayFields[0]); //Object {cdrName: "EQUIPMENTID", type: "date", index: 0}
console.log($.parseJSON(a)); //VM2901:1 Uncaught SyntaxError: Unexpected token o in JSON at position 20

How to prepare a valid json array of objects if i have an array of objects.


You can't append an object to a string. You need to JSON.stringify() the cdrDisplayFields[0] object:

var a = '{"cdrColumnFields":' + JSON.stringify(cdrDisplayFields[0]) + '}';

Note that a much better alternative would be to create an object yourself and then stringify it all together, like this:

var a = JSON.stringify({ cdrColumnFields: cdrDisplayFields[0] });

Also note that turning the above object in to JSON is redundant if all you're going to do is $.parseJSON it back to an object again.