How to parse a JSON string using PHP

2019-01-19 07:45发布

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

标签: php json parsing
4条回答
干净又极端
2楼-- · 2019-01-19 08:33
$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
        )

)
查看更多
贼婆χ
3楼-- · 2019-01-19 08:36

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.

查看更多
Fickle 薄情
4楼-- · 2019-01-19 08:38

JSON_decode and remove escape quotes

查看更多
地球回转人心会变
5楼-- · 2019-01-19 08:46

Use json_decode.

You will need to unescape quotes first; just use

$unescaped_data = str_replace('\"','"',$data)
查看更多
登录 后发表回答