2

I have this string that I generate in JAVA and pass to javascript to be parsed.

This works:

var childString = '[{title: "Item 1"},{title: "Folder 2", isFolder: true,children: [{title: "Sub-item 2.1"},{title: "Sub-item 2.2"}]},{title: "Item 3"}]'; var childArray = eval(childString); 

But I've read everywhere that eval == evil so i'm looking into the JSON way of parsing. I tried using JSON.parse(childString), but I got an error.

How could I do this the JSON way?

Thanks!

7
  • 5
    'but I got an error.' What was the error? Commented Aug 30, 2011 at 15:15
  • 1
    I'm sure you mean eval === evil. :) Commented Aug 30, 2011 at 15:16
  • 2
    jsonlint.com is your friend. Commented Aug 30, 2011 at 15:17
  • @Felix: :) thats pretty cool. invalid json right? Commented Aug 30, 2011 at 15:22
  • 1
    @naveen: Yep, the keys have to be in double quotes. Don't understand your second comment though. Commented Aug 30, 2011 at 15:29

7 Answers 7

7

Your data is valid JavaScript (which is why eval works) but it is not valid JSON. For example you need to surround the name of your properties with quotes.

E.g.

'[{"title": "Item 1"} ... 

You can find the JSON spec here

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

Comments

3

You can't parse it using JSON.parse because your json string is invalid. It needs to be as follows:

var childString = '[{"title": "Item 1"},{"title": "Folder 2", "isFolder": true,"children": [{"title": "Sub-item 2.1"},{"title": "Sub-item 2.2"}]},{"title": "Item 3"}]'; 

See here.

Comments

3

Depending on your browser, you may need to define the JSON object yourself. You can download the code for it from https://github.com/douglascrockford/JSON-js.

Comments

3

Your JSON isn't well formed. You need double quotes on both the keys and the values.

'{"foo":"bar"}' 

Comments

1

Include JSON2 in your HTML output using a script tag, and you can then use JSON.parse.

Comments

1

Ok, jsFiddle:

var childArray = JSON.parse(childString.replace(/([{, ])([a-zA-Z0-9]+):/g, '$1"$2":')); 

will work, but I might still try to get valid JSON instead.

Comments

1

Note: The double quotes are imperative. THIS WOULD NOT WORK:

var childString = "[{'title': 'Item 1'},{'title': 'Folder 2', 'isFolder': true,'children': [{'title': 'Sub-item 2.1'},{'title': 'Sub-item 2.2'}]},{'title': 'Item 3'}]"; 

1 Comment

The double quotes needed to be passed within the string. So you need to single quote the object '[ ..... ]' and have the double quotes internally '[ ""...""..."" ]'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.