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!

Ben
  • 10,020
  • 21
  • 94
  • 157

7 Answers7

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

Matt
  • 43,482
  • 6
  • 101
  • 102
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.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
3

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

'{"foo":"bar"}'
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
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.

Icarus
  • 63,293
  • 14
  • 100
  • 115
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'}]";
Paul V
  • 351
  • 3
  • 9
  • The double quotes needed to be passed within the string. So you need to single quote the object '[ ..... ]' and have the double quotes internally '[ ""...""..."" ]'. – Paul V May 06 '14 at 13:17
1

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

Femi
  • 64,273
  • 8
  • 118
  • 148
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.

Joe
  • 80,724
  • 18
  • 127
  • 145