2014-02-19 61 views
-2

我想通过Python迭代JSON数组。 我有这样的JSON数组:通过Python中的JSON对象进行迭代

{ 
"test1": "Database", 
"testInfo": { 
    "memory": "0.1 % - Reserved: 31348 kb, Data/Stack: 10 kb", 
    "params": { "tcp": " 0" }, 
    "test2": 100, 
    "newarray": [{ 
     "name": "post", 
     "owner": "post", 
     "size": 6397},] 
    } 
} 

我怎样才能检索到 测试1的值: testinfo:和testinfo内(内存..) newarray

非常感谢您的帮助!

+0

Json数组,以什么形式?一个文件对象,一个字符串? – aIKid

+0

数组就像字符串 – user2739823

+0

在JSON术语中,他们称之为对象。用Python术语来说,它是一本字典。只有PHP调用这个数组。 –

回答

3
from json import loads 

# This is a string, we need to convert it into a dictionary 
json_string = '{ 
    "test1": "Database", 
    "testInfo": { 
    "memory": "0.1 % - Reserved: 31348 kb, Data/Stack: 10 kb", 
    "params": { "tcp": " 0" }, 
    "test2": 100, 
    "newarray": [{ 
     "name": "post", 
     "owner": "post", 
     "size": 6397},] 
    } 
}' 

# This is done by converting the string into a dictionary 
# and placing it in a "handle" or a "container", in short.. a variable called X 
x = loads(json_string) 

# Now you can work with `x` as if it is a regular Python dictionary. 
print(x) 
print(x['test1']) 
print(x['testInfo']['memory']) 

# To loop through your array called 'newarray' you simply do: 
for obj in x['testInfo']['newarray']: 
    print(obj) 

Baisc python在你真的使用过loads之后。

+0

非常感谢!我不明白我如何迭代这个数组。在你的例子中x是特定的数字,但是如果我不知道json数组中的对象的数量呢? – user2739823

+0

'x'不是一个数字,它是转换后的JSON字符串obve ..坚持... – Torxed

+0

只需通过'x'循环。从每次迭代中检索你需要的值。 – aIKid