I have the following code from my php script.
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. When I run the following code I got this error in my chrome console:
Uncaught SyntaxError: Unexpected token 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.
As you generate this in PHP, simply don't put the quotes and no parsing is needed :
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.
If you are printing JSON from PHP why don't just keep the array in PHP and then print
print "var obj = " . json_encode($array);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.