2014-09-12 66 views
0

我有以下Python字典对象(JSON模式) - 一个是字典列表元素 -处理字典对象在Python

[ 
    { 
    "id": 101, 
    "type": "fruit", 
    "name": "apple" 
    }, 
    { 
    "id": 102, 
    "type": "fruit", 
    "name": "mango" 
    }, 
    { 
    "id": 103, 
    "type": "vegetable", 
    "name": "cabbage" 
    }, 
    { 
    "id": 104, 
    "type": "vegetable", 
    "name": "carrot" 
    } 
] 

有人可以告诉我怎么可以操纵字典对象的这个名单,我希望下面的输出B: -

[ 
    { 
    "id": 102, 
    "type": "fruit", 
    "name": "mango" 
    } 
] 

我试着这样做: -

import json 

for myObj in A: 
    if myObj['id'] == 102: 
     myVal = myObj 
test = json.dumps(myVal) 
my_op = json.loads(test) 

但THI s不起作用,因为它正在返回我“unicode”类型,但我希望字典“list”作为它的类型。

解决方案: -

import json 

for myObj in A: 
    if myObj['id'] == 102: 
     myVal = [myObj] # Add myObj to list again which fixes the issue 
test = json.dumps(myVal) 
my_op = json.loads(test) 
+0

新增解决以上! – COD3R 2014-09-12 11:08:31

回答

3
import json 

for myObj in A: 
    if myObj['id'] == 102: 
     myVal = [myObj] 
test = json.dumps(myVal) 
B = json.loads(test) 
print B 
+0

谢谢。这解决了这个问题:) – COD3R 2014-09-12 11:09:23

1

你需要把myVal到列表中再次:

myVal = [myObj] 

这将产生:

[{u'type': u'fruit', u'id': 102, u'name': u'mango'}] 

通过json.dumps()/json.loads()运行它之后。 Unicode字符串是完全正常的; JSON始终使用Unicode字符串。

+0

我确实错过了再次将它添加到列表中! – COD3R 2014-09-12 11:10:12

0

有几种方法可以实现这一点。我可能会使用:

import json 
myVal = filter(lambda x: x['id'] == 102, A) 
test = json.dumps(myVal)