I have a JSON String like this.
{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}
I wanted to convert it to object like this
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]
I did figure that out like this.
'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"} + ']'
And using $.parseJSON()
to make it a JSON.
But instead of concatenating. Is there any elegant way to do it?
If so please do share me.
Thanks in advance.
var jsonobj = $. parseJSON(jsonString); There is no need to convert it into an object first just parse the string into a var and it wil lbe an object for you to use.
The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. Some of the examples of malformed JSON strings that can cause an exception on passing are given as follows -
JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
JSONParse like this: https://api.jquery.com/jQuery.parseJSON/
var jsonobj = $.parseJSON(jsonString);
There is no need to convert it into an object first just parse the string into a var and it wil lbe an object for you to use.
Try to push that object into an array,
var xObj = {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"};
var xArr = [];
xArr.push(xObj);
console.log(JSON.stringify(xArr)); //[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With