开发者

JSON to JavaScript object #text property

I am currently developing a JavaScript add-on which receives JSON from an API. So far, so good I retrieve the JSON and then use eval() to convert this JSON to a JavaScript object. This is where the problems start.

My JSON contains a '#text'-property. I evaluated the JavaScript object and found it also has this '开发者_JS百科#text'-property, but I can not call the property since variables with hash-tags are not accepted.

I know two possible solutions (use eval() to convert to an Array or remove the hast-tag), but I would prefer calling the property. Any ideas? Thanks.


You can reference object properties with square brackets:

var obj = {'#foo': 'bar'};
obj['#foo']; // 'bar'

Indeed, obj.#foo is invalid (i.e. will raise a syntax error), but the above method is fine.

Also, don't use eval unless you have to. Despite being a slower solution, it's less safe, especially considering there are usually so many native JSON methods, and most JSON libraries will introduce the functionality only if the native methods don't exist.


Don't use eval, especially for this. You a json parser, modern browsers already have them.

var myObj = JSON.parse(returnFromServer);
console.log(myObj.firstProperty); // etc

Here's a CDN link for json2 http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js


Do stuff before eval like replacing hash sign with something else.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜