简体   繁体   English

如何将字符串解析为JSON对象

[英]How to parse string as JSON object javascript

I have the following code from my php script. 我的php脚本中有以下代码。

var str = "[{id : 'Gadji Tallo', poste : 'attaquants', taille : '1.85m', poids :'77kg', age :'20'},{id:'Mbaye Diagne', poste :'attaquants', taille : '', poids :'', age :'22'},{id:'Sigamary Diarra', poste :'attaquants', taille : '1.76m', poids :'74kg', age :'29'}]";
var result = JSON.parse(str)

what I want is to parse it as JSON to loop through it. 我想要的是将其解析为JSON以遍历它。 When I run the following code I got this error in my chrome console: 当我运行以下代码时,我在chrome控制台中收到此错误:

Uncaught SyntaxError: Unexpected token i 未捕获的SyntaxError:意外的令牌i

Any clue / help is welcom. 欢迎您提供任何线索/帮助。 Thanks 谢谢

This isn't JSON but it's almost a literal JavaScript Object and you don't seem to really need JSON. 这不是JSON,但几乎是一个文字JavaScript对象,您似乎并不需要JSON。

As you generate this in PHP, simply don't put the quotes and no parsing is needed : 当您在PHP中生成此代码时,只需不用引号,也无需解析:

var result = [{id : 'Gadji Tallo', poste : 'attaquants', taille : '1.85m', poids :'77kg', age :'20'},{id:'Mbaye Diagne', poste :'attaquants', taille : '', poids :'', age :'22'},{id:'Sigamary Diarra', poste :'attaquants', taille : '1.76m', poids :'74kg', age :'29'}];

You also need to also put quotes around the names, for example: 您还需要在名称周围加上引号,例如:

var str = '[{"id" : "Gadji Tallo", "poste" : "attaquants", "taille" : "1.85m", "poids":"77kg", "age" :"20"}]';

when parsing JSON from a string. 从字符串解析JSON时。

If you are printing JSON from PHP why don't just keep the array in PHP and then print 如果要从PHP打印JSON,为什么不只是将数组保留在PHP中然后打印

print "var obj = " . json_encode($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM