开发者

Use JSON parse instead of eval

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!


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


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.


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.


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

'{"foo":"bar"}'


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


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.


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'}]";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜