2017-03-12 111 views
0

我有一個json,我想通過python獲取它的一個元素。 JSON的是這樣的:獲取json的元素?

{"$id":"1","Data": 
[{"$id":"2","ArticleId":39511,"Title":"a","Order":39,"TotalCount":0}, 
{"$id":"3","ArticleId":345921,"Title":"a","Order":21,"TotalCount":0}, 
{"$id":"4","ArticleId":43289,"Title":"a","Order":18,"TotalCount":0}, 
{"$id":"5","ArticleId":39540,"Title":"a","Order":16,"TotalCount":0}, 
{"$id":"6","ArticleId":963167,"Title":"a","Order":15,"TotalCount":0}, 
{"$id":"7","ArticleId":519284,"Title":"a","Order":14,"TotalCount":0}, 
{"$id":"8","ArticleId":109699,"Title":"a","Order":13,"TotalCount":0}, 
{"$id":"9","ArticleId":43466,"Title":"a","Order":12,"TotalCount":0}, 
{"$id":"10","ArticleId":39510,"Title":"a","Order":10,"TotalCount":0}, 
{"$id":"11","ArticleId":43307,"Title":"a","Order":9,"TotalCount":0}, 
{"$id":"12","ArticleId":715048,"Title":"a","Order":9,"TotalCount":0}, 
{"$id":"13","ArticleId":133952,"Title":"a","Order":8,"TotalCount":0}, 
{"$id":"14","ArticleId":459712,"Title":"a","Order":8,"TotalCount":0}, 
{"$id":"15","ArticleId":11503,"Title":"a","Order":7,"TotalCount":0}],"TotalCount": 
14,"Id":"0","IsSuccess":true,"Message":"OK","StatusCode":200,"ValidationMessages": 
null,"Exception":null} 

在Python中我使用:

mydata = json.loads(response.text) 

現在我想知道如何使用MYDATA得到的字符串。我的意思是「一」

+0

你想提取'標題'屬性值? – RomanPerekhrest

+2

mydata是一個包含$ id,Data和其他字段的字典。數據是您想要Title屬性的字典列表。 'title = [i ['Title'] for my mydata ['Data']]'會給你一個標題列表。 – algrebe

+0

這看起來像一些mongo查詢輸出。如果是的話,你可以只使用聚合管道提取查詢時需要的內容,而不是使用python解析整個數據。 –

回答

0

你可以做到這一點:

mydata = json.loads(response_text) 
titles = [dct['Title'] for dct in mydata['Data']] 

的一個好方法,以幫助數字像這樣的事情了,是先做這樣的事情:

print(json.dumps(mydata, indent=4)) 

其中,在這種情況下,顯示在類似這樣的結果:

{ 
    "Exception": null, 
    "$id": "1", 
    "ValidationMessages": null, 
    "IsSuccess": true, 
    "TotalCount": 14, 
    "Message": "OK", 
    "Data": [ 
     { 
      "$id": "2", 
      "TotalCount": 0, 
      "ArticleId": 39511, 
      "Order": 39, 
      "Title": "a" 
     }, 
     { 
      "$id": "3", 
      "TotalCount": 0, 
      "ArticleId": 345921, 
      "Order": 21, 
      "Title": "a" 
     }, 
      ..., etc, 
     { 
      "$id": "15", 
      "TotalCount": 0, 
      "ArticleId": 11503, 
      "Order": 7, 
      "Title": "a" 
     } 
    ], 
    "Id": "0", 
    "StatusCode": 200 
} 

從這一點,它通常變得相對Ë asy來確定你需要做什麼來訪問對象的任何部分或部分。