2014-01-27 28 views
0

我有我穿過json.loads以下JSON數據:Python的問題與得到的數據出來json.loads的

{ 
    "meta":{ 
     "limit":20, 
     "next":null, 
     "offset":0, 
     "previous":null, 
     "total_count":2 
    }, 
    "objects":[ 
     { 
     "attributes":"{u'_code': u'[ON CODE]/[OFF CODE]', u'_type': u'pick actuator or sensor', u'code': u'AF126E/AF1266', u'type': u'actuator'}", 
     "id":1, 
     "module":"/api/v1/module/1/", 
     "moduleName":"rfm_ninjablock (ninjablock)", 
     "name":"HallwayLight" 
     }, 
     { 
     "attributes":"{u'_code': u'[ON CODE]/[OFF CODE]', u'_type': u'pick actuator or sensor', u'code': u'0x53df5c', u'type': u'sensor'}", 
     "id":2, 
     "module":"/api/v1/module/1/", 
     "moduleName":"rfm_ninjablock (ninjablock)", 
     "name":"ToiletDoor" 
     } 
    ] 
} 

我試圖擺脫它所有的數據,但我m無法引用數據。 我的代碼如下:

for object in r['objects']: 
     for attributes in object.iteritems(): 
       print attributes 

這給了我:

(u'attributes', u"{u'_code': u'[ON CODE]/[OFF CODE]', u'_type': u'pick actuator or sensor', u'code': u'AF126E/AF1266', u'type': u'actuator'}") 
(u'moduleName', u'rfm_ninjablock (ninjablock)') 
(u'id', 1) 
(u'module', u'/api/v1/module/1/') 
(u'name', u'HallwayLight') 
(u'attributes', u"{u'_code': u'[ON CODE]/[OFF CODE]', u'_type': u'pick actuator or sensor', u'code': u'0x53df5c', u'type': u'sensor'}") 
(u'moduleName', u'rfm_ninjablock (ninjablock)') 
(u'id', 2) 
(u'module', u'/api/v1/module/1/') 
(u'name', u'ToiletDoor') 

我真的不知道這些引用,或者如果確實是我做的是正確的。

屬性已包含JSON,因爲它是如何存儲在數據庫中的。

+0

什麼是你想訪問或試圖做? –

+0

檢索每個項目的屬性 – PythonLearner

回答

2

原始數據序列化的方式有問題。每個元素的attributes字典沒有被序列化爲一組嵌套字典,而是作爲包含內部字典的Python字符串表示的外部字典。

您應該發佈做過原始序列化的代碼。

+0

它來自tastypie – PythonLearner

0

正如字典中的屬性作爲一個字符串表示我用下面的代碼,將其轉換爲字典結束:

for object in r['objects']: 
    attrib = [] 
    attrib = ast.literal_eval(object['attributes']) 
    print attrib['code']