0

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.

3
  • 3
    {subject: Hello} isn't a valid JSON, so either make it valid (adding " around keys and values), or parse it yourself Commented Jan 24, 2012 at 11:27
  • How did you create "phrase": "{subject: Hello}"? You should fix your code at that end and create valid JSON or a valid JavaScript object. Also be careful with the terminology. JSON is a data exchange format, not a data type. I assume you want to create a JavaScript object out of "{subject: Hello}". If you really want some help, you have to provide more information. Commented Jan 24, 2012 at 11:29
  • I am getting a large json object from from a java program. this large json in turn contains a a key (i.e. "phrase") value ("{subject: Hello}") pair whose value (means "{subject: Hello}") itself is supposed to be a json object. Commented Jan 25, 2012 at 6:19

4 Answers 4

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

{subject: Hello} is not JSON.
1

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.

Comments

0

Use JSON.parse():

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

Here is the demo.

Comments

0

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

2 Comments

{subject: Hello} is not JSON.
sorry I didn't notice the missing quotes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.