Having trouble with accessing json values formed from php array
var latlag = '<?php echo json_encode($coordinates); ?>';
alert(latlng) produces:
[{
"1280":{"lat":"-1.197070","lng":"-1.197070"},
"1239":{"lat":"-1.222410","lng":"-1.222410"},
"1258":{"lat":"-1.153020","lng":"-1.153020"},
...
}]
I’ve tried all sorts of ways to access lat and lag for a specific ID and the only result other than undefined has been the nth character of latlng as if its being treated like a string?!
alert(latlng[10]); # {
alert(latlng[1280]['lat]); # undefined
alert(latlng['1280'].lat); # undefined
You don’t want to put the JSON in quotes, so:
(Technically, that’s not JSON at all, it’s a JavaScript object initializer. But that’s fine, JSON is a subset of initializer syntax and so all valid JSON texts are also valid JavaScript initializers.)
If the structure is really as you’ve quoted it, it’s an array with one entry, which is an object with properties with names like
1280and1258, whose values are objects with properties namedlatandlng. So you’d access those like this:latlngis the array,latlng[0]is the one object it holds, andlatlng[0]["1280"]is the{"lat":"-1.197070","lng":"-1.197070"}object.You may be wondering why I’ve used quotes around
1280above. It’s because those keys are clearly given as strings (as is required in JSON, though not in JavaScript initializers), and so I can’t be sure there aren’t entries like"0012". Property names are always strings even when not written as strings, solatlng[0][1280]andlatlng["0"]["1280"]both mean the same thing (because the0and the1280are converted to string [yes, really]), but naturallylatlng[0]["0012"]is not the same aslatlng[0][12]because the latter uses"12", not"0012", as the property name. If you know you won’t have leading zeros, you can ditch the quotes.