Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

json string accessing different {} objects with php

I have some JSON code in a string that I am trying to parse. I havent used JSON much so this is prolly a simple question.

It is like:

$json_code =" 
    {
    "key1":"value",
    "key2":"value"
    },
    {
    "key3":"value",
    "key4":"value"
    }";

Im having problems trying to loop through all of different Objects(? - the sets of curly braces) with php.

Any help is greatly appreciated

Thanks, Bryan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't use a JSON literal in PHP like that. Turn it into a string (wrap it in quotes), and then use json_decode() to access it in an object like manner.

If you'd prefer to access it like an array, set json_decode()'s second argument to TRUE.

Update

I see you have wrapped it in quotes - you must now escape the inner quotes.

To loop through it, just use foreach() on the object or array returned from json_decode().

To visualise the structure once parsed via json_decode(), use var_dump().

Update

Your problem is, your JSON is not proper - it has 2 objects, but not in array literal syntax. You need to wrap that structure with [].

See it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...