开发者

php json decode - get a value

I'm trying to extract a specific value from json content . Here it is link with the json code http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521 As you may see the the code displayed is

json({items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}); 
I need to extract the first url which in this case is "http://fairfield.ebayclassifieds.com/" and its name value which is "Fairfield" , I could do it with regex but I would prefer to use json_decode. Unfortunately when I try to decode it doesn't work

$json  = getContent("http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514开发者_运维知识库&lng=-74.0437521");
$test = json_decode($json, true);


As danp already said, the returned JSON is enclosed in a function call (specified by jsoncallback=json). You cannot get rid of this totally but, just using AreaSearch?jsoncallback=&lat=41.1131514&lng=-74.0437521 removes at least the json at the beginning of the string and you can get rid of the brackets by:

$json = trim(trim($json), "();");

with gives:

{items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}

Unfortunately, the JSON string is not valid. The keys (items, url, ...) have to be enclosed in quotes ". You can easily check that you get a syntax error with json_last_error() (error code 4, JSON_ERROR_SYNTAX).

Update:

According to this question: Invalid JSON parsing using PHP , you can make the JSON string valid with:

$json = preg_replace('/(\w+):/i', '"\1":', $json);

This encloses the keys in quotes.


If the string would be valid, then you could generate an array via:

$a = json_decode($json, true);

which would give you:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [url] => http://fairfield.ebayclassifieds.com/
                    [name] => Fairfield
                )
            [1] => Array
                (
                    [url] => http://newyork.ebayclassifieds.com/
                    [name] => New York City
                )
        )
    [error] => 
)

So you could get the first URL and name via $a['items'][0]['url'] and $a['items'][0]['name'] resp.


But I repeat, the JSON you get as response is not valid and you cannot parse it with json_decode() in its original form.


Its not valid JSON. The keys should be wrapped inside quotes.

You can validate your json using the excellent JSON Lint site.

This is a valid version of the data returned:

 {
"items": [
    {
        "url": "http://fairfield.ebayclassifieds.com/",
        "name": "Fairfield"
    },
    {
        "url": "http://newyork.ebayclassifieds.com/",
        "name": "New York City"
    }
],
 "error": "null"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜