2013-05-30 38 views
0

我在訪問JSON代碼中的某個屬性(hlink)時遇到問題。這是因爲JSON輸出的結構並不總是相同的,因此我得到以下錯誤:「不能使用stdClass類型的對象作爲...中的數組」。有人可以幫我解決這個問題嗎?解析具有不同結構的JSON數據

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(); 
} 
+0

基本上,你必須得到解析JSON並檢查它,看你有什麼。 (如果我們知道你正在使用的是什麼語言,這會有所幫助,我在猜測JavaScript,但我不確定) –

+0

如果看到另一端發送單個「對象」的情況很常見只有一個,但如果有多個對象則是一系列對象。我在這種情況下使用的一個技巧是檢查未解析的JSON源的第一個字符,並且如果它在字符串周圍是'{',slap'[]'將其轉換爲單元素數組。然後無論如何,解析的JSON都可以得到相同的處理。 –

+0

你沒有使用str = JSON.stringify(obj)和JSON.parse(str)? 以上是什麼樣的元語法?它不是JSON。 爲什麼不提供最小有效的JSON示例來開始? – stackunderflow

回答

0

假設這是PHP的,你知道JSON總是包含一個對象或一組對象,問題歸結爲檢測您收到的內容。

嘗試類似:

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

是這個作品,謝謝! – user2400821

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