me_digvijay
me_digvijay

Reputation: 5492

getting json from string

I have the following json object

"phrase": "{subject: Hello}"

When I access "phrase" it returns "{subject: Hello}" as a string but I want this string to be converted to json object.

Upvotes: 0

Views: 1179

Answers (4)

Guffa
Guffa

Reputation: 700362

If it's a Javascript object literal, just remove the quotation marks when you create it:

var phrase = { subject: "Hello" };

If it's a JSON string that is parsed, change the string to an object:

{ "phrase": { "subject": "Hello" } }

If you have a variable that contains a JSON string, you need to make it valid JSON to parse it:

var phrase = '{ "subject": "Hello" }';
var obj = JSON.parse(phrase);

You can also parse the string as Javascript, which has a more relaxed syntax. The string value needs delimiters though:

var phrase = '{ subject: "Hello" }';
var obj = eval(phrase);

Note that the eval function actually executes the string as javascript, so you need to know where the string value comes from for this to be safe.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

you could use native JSON parsing with JSON.parse(jsonString);
(Edit: assuming to have a valid JSON object)

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

Use JSON.parse():

var obj = {myObj:"{\"this\":\"that\"}"};
obj.myObj = JSON.parse(obj.myObj);
alert(obj.myObj["this"]);

Here is the demo.

Upvotes: 0

hugomg
hugomg

Reputation: 69934

There is a function called JSON.parse to convert things from strings to objects but I am not sure it would apply to your case, since you have invalid JSON (the "Hello" not being quoted is a bid deal and the "subject" not being quoted is a bad sign)

Upvotes: 1

Related Questions