How to parse a JSON string using PHP
Solution 1
$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
)
)
Solution 2
Use json_decode.
You will need to unescape quotes first; just use
$unescaped_data = str_replace('\"','"',$data)
Solution 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.
Solution 4
JSON_decode and remove escape quotes
Related videos on Youtube
Genadinik
Thank you to everyone who has helped me. I am extremely appreciative of the amazing people on StackOverflow who have helped me :) I currently run https://www.problemio.com under which I offer mobile apps, books, coaching, and online courses, and even a B2B course licensing business: https://www.problemio.com/udemy/white-labeling-or-buying-udemy-courses.html I also run a funny t-shirt store: https://www.waveifyoulike.com
Updated on April 03, 2020Comments
-
Genadinik about 4 years
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
-
Marc B@lucifurious: probably because magic_quotes_gpc is turned on.
-
ysrbtry json_decode
-
lucifuriousWhy does it have those slashes in it??
-
-
mickmackusa about 2 yearsThis is not enough. The input string would still not be valid json after calling
str_replace()
.