2014-07-15 63 views
0

我想每次都能訪問「uuid」,這是該代碼中的兩次,並且還可以訪問「cloud_uuid」。身體就像下面的東西:如何解析json正文,就像列出的字典

{ 
"computes": [{ 
    "uuid": "110c607a-231c-4724-be7f-db5ed388158", 
    "name": "9.4.98.33", 
    "description": null, 
    "version": "1.0", 
    "type": "compute", 
    "number_of_vms": 0, 
    "status": "ACTIVE", 
    "provisioning_status": { 
     "status": "COMPLETED", 
     "started_at": "", 
     "updated_at": "", 
     "status_data": null 
    }, 
    "health_status": { 
     "status": "OK", 
     "alerts": [], 
     "updated_at": "2014-07-11T17:09:12.194000" 
    }, 
    "compliance_status": { 
     "compliance_reasons": null, 
     "is_compliant": true, 
     "updated_at": null 
    }, 
    "run_priority_order": null, 
    "created": "2014-07-11T16:01:32.837821", 
    "updated": "2014-07-11T17:08:16.031838", 
    "capability_categories": { 
     "v": [{ 
      "name_key": "", 
      "description_key": "", 
      "version": "0", 
      "hidden": t, 
      "priority": 1, 
      "name_nls": "", 
      "description_nls": "" 
     }], 
     "monitoring": [{ 
      "name_key": "m", 
      "description_key": null, 
      "version": "1.0", 
      "hidden": true, 
      "priority": 100, 
      "name_nls": "monitoring", 
      "description_nls": null 
     }], 
     "scheduler": [{ 
      "name_key": "", 
      "description_key": null, 
      "version": "1.0", 
      "hidden": false, 
      "priority": 20, 
      "name_nls": "", 
      "description_nls": null 
     }], 
     "network": [{ 
      "name_key": "", 
      "description_key": "", 
      "version": "1.0", 
      "hidden": false, 
      "priority": 10, 
      "name_nls": "", 
      "description_nls": "" 
     }] 
    }, 
    "links": [{ 
     "href": "", 
     "rel": "self" 
    }, { 
     "href": "", 
     "rel": "bookmark" 
    }], 
    "cloud_uuid": "b603e16e-38a6-435e-9359-79c27fee93a", 
    "operating_system_uuid": "70f605e7-6512-49b4-833c-b25d47823a4" 
}, { 
    "uuid": "7383f4a5-dc0a-420b-806c-abbd49c1655a", 
    "name": "9.4.193.20", 
    "description": null, 
    "version": "1.0", 
    "type": "compute" 

你能與下面的幫助,我試圖代碼爲回答評論: 假設身體是「雲」,而不是「計算」 我試過的東西,如得到cloud_uuid :cloud_uuid = ((e['cloud_uuid']用於edict['clouds'] if e['name'] == name_to_find), None) 它拋出無錯誤>

cloud_uuid = ((e['cloud_uuid'] for e in dict['clouds'] if e['name'] == name_to_find), None) TypeError: 'type' object is unsubscriptable

+1

你在哪個語言編碼?你能格式化你的JSON嗎? – JDong

回答

0

在蟒它是非常簡單的:

[(e['uuid'], e['cloud_uuid']) for e in dict['computes']] 

編輯: 它看起來像我忽略了一對方括號。試試:

[(_['computes'][0]['uuid'], _['cloud_uuid']) for _ in data] 
+0

我試着用類似cloud_uuid的方式獲得cloud_uuid =((e ['cloud_uuid'] for e in dict ['clouds'] if e ['name'] == name_to_find),None),,,它拋出error- > cloud_uuid =((e ['cloud_uuid'] for e in dict ['clouds'] if e ['name'] == name_to_find),None) TypeError:'type'object is unsubscriptable – user3625349