I have a JSON string that has 1-n numbers of lat/lng records. It looks something like this:
{\"lat\":37.790388261934424,\"lng\":-122.46047996826172},{\"lat\":37.789608231530124,\"lng\":-122.46344112701416}
What is a good way to parse this to get lat/lng values loop? And do the escaped double quotes impact the parsing?
Thanks, Alex
asked Apr 3, 2011 at 1:52
-
1try json_decodeysrb– ysrb2011年04月03日 01:54:32 +00:00Commented Apr 3, 2011 at 1:54
-
1Why does it have those slashes in it??lucifurious– lucifurious2011年04月03日 02:05:59 +00:00Commented Apr 3, 2011 at 2:05
-
Because it is wrapped in double quotes.Dejan Marjanović– Dejan Marjanović2011年04月03日 02:10:26 +00:00Commented Apr 3, 2011 at 2:10
-
1@lucifurious: probably because magic_quotes_gpc is turned on.Marc B– Marc B2011年04月03日 02:13:55 +00:00Commented Apr 3, 2011 at 2:13
4 Answers 4
$ll = '[{"lat":37.790388261934424,"lng":-122.46047996826172},{"lat":37.789608231530124,"lng":-122.46344112701416}]';
$ll = json_decode($ll);
print_r($ll);
Prints...
Array
(
[0] => stdClass Object
(
[lat] => 37.7903882619
[lng] => -122.460479968
)
[1] => stdClass Object
(
[lat] => 37.7896082315
[lng] => -122.463441127
)
)
answered Apr 3, 2011 at 1:59
1 Comment
mickmackusa
This answer is missing its education explanation.
Use json_decode.
You will need to unescape quotes first; just use
$unescaped_data = str_replace('\"','"',$data)
answered Apr 3, 2011 at 1:53
1 Comment
mickmackusa
This is not enough. The input string would still not be valid json after calling
str_replace()
.In your case it's probably best to use:
$array = json_decode(stripslashes("[$input_string]"), 1);
Note that you will lose some precision on your float values in PHP.
answered Apr 3, 2011 at 1:58
4 Comments
Genadinik
Is there a way to preserve the precision of the float values in PHP with this operation? They float values are pretty important.
Dejan Marjanović
If he wrapped it in double quotes, he doesn't need to escape string. His JSON is missing
[]
around {},{}
like you have shown. @Genadinik, 9 decimals is not enough for Lat and Lon?mario
@Genadinik: Not with json_decode. And you cannot handle more precise numbers in PHP, it only knows
float
. The lost precision is minimal, and I actually suspect the Javascript representation is not overly exact either. (A workaround would involve parsing by hand, and using the gmp functions for all coordinates: php.net/manual/en/ref.gmp.php - in your whole application.)Salvatore Pannozzo Capodiferro
It works form me, even though the data are inserted into array, so I have to retrieve it using array[0]['data']
JSON_decode and remove escape quotes
answered Apr 3, 2011 at 1:56
Comments
lang-php