2012-03-10 33 views
0

JSON是坐在我的本地主機爲:/數據/:JSON進來的對象不是字符串

{ 
"children": [ 
    { 
     "name": "analytics", 
     "size": "1243" 
    }, 
    { 
     "name": "math", 
     "size": "4343" 
    }, 
    { 
     "name": "algebra", 
     "size": "1936" 
    }, 
    { 
     "name": "calc", 
     "size": "3936" 
    }, 
    { 
     "name": "geom", 
     "size": "2136" 
    }, 
    { 
     "name": "Quant", 
     "size": "4136" 
    } 
] 

}

這裏是我正在試圖訪問JSON:

var interval = setInterval(function() { 
     $.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) { 
      $.each(json.children,function(i,name){ 
      alert(json.children); 
      }); 

     }); 
     }, 3000); 

數據進來很好。也就是說,當我運行console.log(json)我可以在firebug中看到上面的json名稱/值txt對。但是,在每個名稱值對之前,我會看到Object這個詞。因此,例如,而不是我的日誌顯示{name =「analytics」,size =「1243」},它實際上顯示:[Object {name =「analytics」,size =「1243」},...而且,是我的警報顯示:[對象對象]而不是name =「analytics」,size =「1243」。 這是爲什麼,有沒有辦法讓我的JSON名稱/值對在文本中,以便我可以存儲爲JavaScript字符串?

非常感謝提前。

回答

1

O在JSON中代表「對象」。這是一種將JavaScript對象序列化爲字符串的方法(並返回)。您似乎一方面依靠轉換(參考children),但不希望另一方面完成轉換。如果您真的想要children成爲您所描述格式的字符串集合,則應該以此方式存儲它。如果您確實需要對象符號(並轉換爲客戶端中的對象),那麼您可以簡單地使用該對象的屬性。

var interval = setInterval(function() { 
    $.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) { 
     $.each(json.children,function(i,item){ 
      alert("name = " + item.name + ", size = " + item.size); 
     }); 

    }); 
    }, 3000); 
+0

Ahhhhhhh!我明白......就是這樣。最後。我無法得到這個描述(obj to str)來點擊。非常感謝你做的這些!! – Chris 2012-03-10 14:09:48

2

當使用jQuery.getJSON或將響應指定爲JSON時,jQuery會自動解碼響應。如果您想要簡單的回覆,請改爲使用jQuery.ajax

+0

其實,jQuery.getJSON是Ajax調用的簡寫。查看ajax方法的jQuery.getJSON頁面。 – 2012-03-10 13:56:08

+0

@JessevanAssen不完全是'$ .getJSON'隱式設置'dataType:json',與'$ .ajax'一樣,您可以靈活地將'dataType'指定爲'text'等。 – Rafay 2012-03-10 13:59:05

+1

不,我的意思是'jQuery.getJSON'實際上調用了帶有一些默認參數的'jQuery.ajax'方法,如[jQuery.getJSON](http://api.jquery.com/jQuery.getJSON/)頁面所示。 – 2012-03-10 14:14:23

0

你所說的一切都是螢火蟲和警報的正常行爲。你不能提醒一個對象。

這裏的例子你的$不用彷徨回調

http://jsfiddle.net/Y3N4S/

$.each(json.children, function(i, item){ 
    $('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>') 

}) 
0

內響應好,工作對象是如何循環的打算的"Javascript Object Notation"

其實,你的json是一個對象數組。

{ 
    "children": [ // <-- Array 
      {...},// <- Object 
      {...} // <- Object 
    ] 
} 

您可以訪問您的鍵值對這樣:children[0].name

for (var i=0;i< children.length; ++){ 
    console.log(children[i].name); 
    console.log(children[i].size); 
}