Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON String to Object - jquery [closed]

I have a JSON String like this.

{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}

I wanted to convert it to object like this

[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}]

I did figure that out like this.

'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} + ']'

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.

like image 983
Unknown User Avatar asked Apr 26 '14 12:04

Unknown User


People also ask

How to convert string into object in jQuery?

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.

What is parseJSON in jQuery?

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 -

What is parseJSON?

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.

What is JSON Stringify?

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.


2 Answers

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.

like image 74
Rookasaur Avatar answered Sep 29 '22 23:09

Rookasaur


Try to push that object into an array,

var xObj = {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"};
var xArr = [];
xArr.push(xObj);

console.log(JSON.stringify(xArr)); //[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}];
like image 24
Rajaprabhu Aravindasamy Avatar answered Sep 29 '22 22:09

Rajaprabhu Aravindasamy