最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing Json fields with weird characters - Stack Overflow

programmeradmin0浏览0评论

i have a json string im converting to object with a simple eval(string);

heres the sample of the json string:
var json = @'
"{ description" : { "#cdata-section" : "<some html here>" } }
';
var item = eval('('+json+')');

I am trying to access it like so

item.description.#cdata-section

my problem is that javascript does not like the # in the field name.. is there a way to access it?

i have a json string im converting to object with a simple eval(string);

heres the sample of the json string:
var json = @'
"{ description" : { "#cdata-section" : "<some html here>" } }
';
var item = eval('('+json+')');

I am trying to access it like so

item.description.#cdata-section

my problem is that javascript does not like the # in the field name.. is there a way to access it?

Share Improve this question asked Nov 10, 2009 at 18:22 WillWill 1,6224 gold badges25 silver badges39 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13
item.description['#cdata-section']

Remember that all Javascript objects are just hash tables underneath, so you can always access elements with subscript notation.

Whenever an element name would cause a problem with the dot notation (such as using a variable element name, or one with weird characters, etc.) just use a string instead.

var cdata = item.description["#cdata-section"];

While the official spec for JSON specifies simply for chars to be provided as a field identifier, when you parse your JSON into a Javascript object, you now fall under the restrictions of a Javascript identifier.

In the Javascript spec, an identifier can start with either a letter, underscore or $. Subsequent chars may be any letter, digit, underscore or $.

So basically, the # is valid under the JSON spec but not under Javascript.

发布评论

评论列表(0)

  1. 暂无评论