2014-10-20 74 views
0

解析python中的json(來自freebase的響應) 這個問題關於JSON解析。我正在查詢freebase的某些數據並獲取JSON對象。響應具有以下結構解析python中的json(來自freebase的響應)

{ 
    "result": [ 
    { 
     "attribute0": [ 
     "attrbVal0" 
     ], 
     "attribute1": [], 
     "attribute2": "attrbVal1", 
     "attribute3": [ 
     "val1", 
     "val2" 
     ], 
     "creator": "abc", 
     "key": [ 
     "val2", 
     "val3" 
     ] 
    } 
    ] 
} 

請注意,這些屬性對於任何數量的值都可以具有零值。如果沒有值,則表示爲[]或爲空。 屬性集是我不知道的。它改變作爲查詢的變化,所以我不能硬編碼值就像

result['attribute2']; 

從上面的JSON我想要得到的屬性,其中值是[]null。 我曾嘗試下面的事情讓屬性和值,

print response.keys() 

打印結果

for r in response['result']: 
    print r 

打印在一個裏面去結果了一切。那是

print len(result) #prints 1 

我試過以下來獲取屬性列表,但沒有運氣。

result = response['result'] 
elem = json.loads(result); 
keys = elem.keys() 

所以我正在尋找代碼來獲取上述json中的所有鍵值對以及一些解釋指出我的錯誤。

+0

'response [「result」]'是一個字典列表(在你的情況下,單個字典)。 – bereal 2014-10-20 10:51:01

+1

我根據它的實際嵌套結構重新格式化了您的JSON,這會使您的錯誤更加清晰。 – 2014-10-20 10:54:01

回答

2

您可以遍歷字典的項目,爲您提供成對的鍵和值;然後,這可以讓你的價值篩選:

for result in response['result']: 
    for attrname, value in result.items(): 
     if not value: # empty list or None 
      print attrname 

注意response['result']是一個列表,包含(大概)一個或多個字典對象。

在Python兩個空列表和None(Python的等效的JSON null的)被認爲是在布爾上下文假,所以not valueTrue對於其值在原JSON響應一個空列表或null那些屬性。

演示:

>>> response = { 
... "result": [ 
...  { 
...  "attribute0": [ 
...   "attrbVal0" 
...  ], 
...  "attribute1": [], 
...  "attribute2": "attrbVal1", 
...  "attribute3": [ 
...   "val1", 
...   "val2" 
...  ], 
...  "creator": "abc", 
...  "key": [ 
...   "val2", 
...   "val3" 
...  ] 
...  } 
... ] 
... } 
>>> for result in response['result']: 
...  for attrname, value in result.items(): 
...   if not value: # empty list or None 
...    print attrname 
... 
attribute1 

因此,在你的樣品輸入,只有attribute1有一個空值。

+0

你對'len(response)'= 1的假設是正確的,'type(response)'是'dict'。我收到以下錯誤。 'AttributeError:'list'object has no attribute'items'' – Hegde 2014-10-20 11:27:14

+0

@Hegde:啊,我錯過了'response ['result']'是一個列表而不是單個字典的事實。更新。 – 2014-10-20 11:29:42

+0

這工作得很好。謝謝@Martin Pieters – Hegde 2014-10-20 16:40:27