我不知道为什么这不显示任何东西。我试图获取var txt中的信息以在html中动态生成!
function byId (id) {
return document.getElementById(id);
}
var txt = '{"characters":[' +
'{"fullName":"John Doe","speci":"human male","occup":"Web Personality","cide":"Sleeper","descr":"blah","biog":"blarg","allia":"chaos good" },' +
'{"fullName":"Jane Doe","speci":human female",occup":"Movie Producer","cide":"Citric","descr":"bluh","biog":"blurg","allia":"neutral" },' +
'{"fullName":"Canter Doma","speci":alien male",occup":"Chef","cide":"Galv","descr":"bleh","biog":"blerg","allia":"evil" }]}';
var obj = eval ("(" + txt + ")");
byId("fname").innerHTML = obj.characters[1].fullName;
byId("spec").innerHTML = obj.characters[1].speci;
byId("occu").innerHTML = obj.characters[1].occup;
byId("cid").innerHTML = obj.characters[1].cide;
byId("desc").innerHTML = obj.characters[1].descr;
byId("bio").innerHTML = obj.characters[1].biog;
byId("alli").innerHTML = obj.characters[1].allia;
我在这里有测试链接。 http://jsfiddle.net/KLer3/
答案 0 :(得分:1)
多个问题:
JSON.parse
代替eval
。见this。更新小提琴: http://jsfiddle.net/KLer3/4/
答案 1 :(得分:1)
如果您不使用eval,这可能会更好。
你在占领和外星人中缺少引号。
{
"characters":[
{
"fullName":"John Doe",
"speci":"human male",
"occup":"Web Personality",
"cide":"Sleeper",
"descr":"blah",
"biog":"blarg",
"allia":"chaos good"
},
{
"fullName":"Jane Doe",
"speci":"human female",
occup":"Movie Producer",
"cide":"Citric",
"descr":"bluh",
"biog":"blurg",
"allia":"neutral"
},
{
"fullName":"Canter Doma",
"speci": "alien male",
"occup":"Chef",
"cide":"Galv",
"descr":"bleh",
"biog":"blerg",
"allia":"evil"
}
]}
答案 2 :(得分:1)
var obj = eval ("(" + txt + ")");
没有必要我设置它
这是var obj = txt;
的速度。查看您的代码:
立即查看您的代码:http://jsfiddle.net/KLer3/6/
答案 3 :(得分:0)
您的JSON中缺少引号。例如:
"speci":"human female",occup": "Movie Producer",
...缺少“占用”的开头报价(还有更多类似的错误)。
修复这些问题,您的代码可以运行。
但是,使用eval()
解析JSON并不是一个好习惯,因为它允许注入除数据结构赋值之外的代码。
改为使用JSON.parse()
:
var obj = JSON.parse(txt);
我假设你是手工编写JSON字符串作为实验的一种方式。不要在实际代码中执行此操作。使用JSON.stringify()或其等效的服务器端语言。
如果您真的希望您的数据与您的代码内联,那么您根本不需要JSON - 只需将其声明就位:
var obj = { characters: [
{"fullName":"John Doe","speci":"human male", ... },
{"fullName":"Jane Doe","speci":human female", ... },
...
]};
答案 4 :(得分:0)
你有多个语法错误,缺少引号"
- 在假设你做错了之前确保代码写得正确......否则看起来它应该有效......
答案 5 :(得分:0)
您的字符串应如下所示:
var txt='{'
+ '"characters": ['
+ '{'
+ '"fullName": "John Doe",'
+ '"speci": "human male",'
+ '"occup": "Web Personality",'
+ '"cide": "Sleeper",'
+ '"descr": "blah",'
+ '"biog": "blarg",'
+ '"allia": "chaos good"'
+ '},'
+ '{'
+ '"fullName": "Jane Doe",'
+ '"speci": "humanfemale",'
+ '"occup": "Movie Producer",'
+ '"cide": "Citric",'
+ '"descr": "bluh",'
+ '"biog": "blurg",'
+ '"allia": "neutral"'
+ '},'
+ '{'
+ '"fullName": "Canter Doma",'
+ '"speci": "alienmale",'
+ '"occup": "Chef",'
+ '"cide": "Galv",'
+ '"descr": "bleh",'
+ '"biog": "blerg",'
+ '"allia": "evil"'
+ '}'
+ ']'
+'}';
但正如评论中所指出的那样,手工解析并不是最好的做法。