简体   繁体   English

如何使用PHP解析JSON字符串

[英]How to parse a JSON string using PHP

I have a JSON string that has 1-n numbers of lat/lng records. 我有一个JSON字符串,其中包含1-n个lat / lng记录。 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? 解析这个以获得lat / lng值循环的好方法是什么? And do the escaped double quotes impact the parsing? 转义的双引号会影响解析吗?

Thanks, Alex 谢谢,亚历克斯

Use json_decode. 使用json_decode。

You will need to unescape quotes first; 你需要先引用引号; just use 只是用

$unescaped_data = str_replace('\"','"',$data)
$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
        )

)

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. 请注意,在PHP中浮点值会丢失一些精度。

JSON_decode并删除转义引号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM