我想在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
答案 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。