Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON string using PHP

Tags:

json

php

parsing

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

like image 351
Genadinik Avatar asked Apr 17 '26 05:04

Genadinik


2 Answers

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

)
like image 100
Dejan Marjanović Avatar answered Apr 19 '26 05:04

Dejan Marjanović


Use json_decode.

You will need to unescape quotes first; just use

$unescaped_data = str_replace('\"','"',$data)
like image 41
Byron Whitlock Avatar answered Apr 19 '26 05:04

Byron Whitlock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!