2

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
4
  • 1
    try json_decode Commented Apr 3, 2011 at 1:54
  • 1
    Why does it have those slashes in it?? Commented Apr 3, 2011 at 2:05
  • Because it is wrapped in double quotes. Commented Apr 3, 2011 at 2:10
  • 1
    @lucifurious: probably because magic_quotes_gpc is turned on. Commented Apr 3, 2011 at 2:13

4 Answers 4

6
$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

This answer is missing its education explanation.
5

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

This is not enough. The input string would still not be valid json after calling str_replace().
3

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

Is there a way to preserve the precision of the float values in PHP with this operation? They float values are pretty important.
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?
@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.)
It works form me, even though the data are inserted into array, so I have to retrieve it using array[0]['data']
1

JSON_decode and remove escape quotes

answered Apr 3, 2011 at 1:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.