2014-02-19 107 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