在Python中迭代JSON对象

时间:2014-02-19 12:57:24

标签: python json

我想在Python中迭代JSON数组。 我有这个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

1 个答案:

答案 0 :(得分: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)

真正使用loads之后的基本python。