解析具有不同结构的JSON数据

时间:2013-05-30 21:28:18

标签: arrays json

我在访问JSON代码中的某个属性(hlink)时遇到问题。这是因为JSON输出的结构并不总是相同,因此我得到以下错误:“不能使用类型为stdClass的对象作为数组...”。有人可以帮我解决这个问题吗?

JSON输出1(数组)

Array ( 
    [0] => stdClass Object ( 
    [hlink] => http://www.rock-zottegem.be/ 
    [main] => true 
    [mediatype] => webresource ) 
    [1] => stdClass Object ( 
    [copyright] => Rock Zottegem 
    [creationdate] => 20/03/2013 14:35:57 
    [filename] => b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg 
    [filetype] => jpeg 
    [hlink] => http://media.uitdatabank.be/20130320/b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg
)   

JSON输出2

stdClass Object ( 
    [copyright] => Beschrijving niet beschikbaar 
    [creationdate] => 24/04/2013 19:22:47 
    [filename] => Cinematek_F14281_1.jpg 
    [filetype] => jpeg 
    [hlink] => http://media.uitdatabank.be/20130424/Cinematek_F14281_1.jpg 
    [main] => true 
    [mediatype] => photo 
) 

这是我的代码:

try {
    if (!empty($img[1]->hlink)){
        echo "<img src=" . $img[1]->hlink . "?maxheight=300></img>";
    }
}
catch (Exception $e){
    $e->getMessage();
}

2 个答案:

答案 0 :(得分:0)

假设这是PHP,并且您知道JSON始终包含对象或对象数组,问题可归结为检测您收到的内容。

尝试类似:

if (is_array($img)) {
    $hlink = $img[0]->hlink;
} else {
    $hlink = $img->hlink;
}

答案 1 :(得分:0)

这不是直接回答你的问题,而是应该让你有办法调查你遇到的问题。

代码示例

var obj1 = [ new Date(), new Date() ];
var obj2 = new Date();
obj3 = "bad";
function whatIsIt(obj) {
    if (Array.isArray(obj)) {
        console.log("obj has " + obj.length + " elements");
    } else if (obj instanceof Date) {
        console.log(obj.getTime());
    } else {
        console.warn("unexpected object of type " + typeof obj);
    }
}
// Use objects
whatIsIt(obj1);
whatIsIt(obj2);
whatIsIt(obj3);
// Serialize objects as strings
var obj1JSON = JSON.stringify(obj1);
// Notice how the Date object gets stringified to a string
// which no longer parses back to a Date object.
// This is because the Date object can be fully represented as a sting.
var obj2JSON = JSON.stringify(obj2);
var obj3JSON = JSON.stringify(obj3);
// Parse strings back, possibly into JS objects
whatIsIt(JSON.parse(obj1JSON));
// This one became a string above and stays one
// unless you construct a new Date from the string.
whatIsIt(JSON.parse(obj2JSON));
whatIsIt(JSON.parse(obj3JSON));

<强>输出

obj has 2 elements JsonExample:6
1369955261466 JsonExample:8
unexpected object of type string JsonExample:10
obj has 2 elements JsonExample:6
unexpected object of type string JsonExample:10
unexpected object of type string JsonExample:10
undefined