2013-04-08 72 views
1

我正在從JSON中提取一組值並將它們寫入文件。從JSON提取Python的值

的JSON格式如下:

"interactions":  [ 
    { 
     "type": "free", 
     "input":    [ 
      [ 1, 4594, 119218, 0, [71, 46], [2295, 1492], [71, 46], [2295, 1492], 16017, 520790446, [71, 46, 71, 46], [71, 46, 71, 46] ], 
      [ 1, 4594, 119219, 0, [72, 46], [2323, 1492], [72, 46], [2323, 1492], 26016, 520790456, [72, 46, 72, 46], [72, 46, 72, 46] ], 
      [ 1, 4594, 119220, 0, [72, 45], [2323, 1464], [72, 45], [2323, 1464], 26016, 520790466, [72, 45, 72, 45], [72, 45, 72, 45] ], 
      [ 1, 4594, 119221, 0, [72, 45], [2323, 1464], [72, 45], [2323, 1464], 26016, 520790476, [72, 45, 72, 45], [72, 45, 72, 45] ], 
      [ 1, 4594, 119222, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 26016, 520790486, [73, 45, 73, 45], [73, 45, 73, 45] ], 
      [ 1, 4594, 119223, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 26016, 520790496, [73, 45, 73, 45], [73, 45, 73, 45] ], 
      [ 1, 4594, 119224, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 46000, 520790506, [73, 45, 73, 45], [73, 45, 73, 45] ] 
     ] 

我需要什麼來提取,是[71,46]列中,然後其與520790446開始列,並將其寫入到輸出文件。

下面是我在一分鐘得到了代碼:

import json 

json_data = open("test_json.json") 

data = json.load(json_data) 

json_data.close() 

# Need some sort of nested loop here to iterate through each line of the block, and each block also. 
print data["interactions"][0]["input"][0][4], '\t', data["interactions"][0]["input"][0][9] 

有幾個可變長度的這些塊,我需要提取所有的值,直到文件的末尾。雖然我被困在循環結構中。

任何人都可以協助嗎?

回答

2

你可以在像這樣的數據得到:

[x[4] for x in data["interactions"][0]["input"]] 

[x[9] for x in data["interactions"][0]["input"]] 

或一氣呵成,像

[[x[4], x[9]] for x in data["interactions"][0]["input"]] 

要回答的評論的第一部分:

[[x[4], x[9]] for x in interaction["input"] for interaction in data["interactions"]] 
+0

我該如何去在[[交互]]上面([0])之後迭代塊?我相信這是遍歷整個JSON文件的塊。此外,可以輸出到一個.csv文件或類似的每行後面的換行符?例如「[71,46] 520790446」在每一行上。 – Matthew 2013-04-08 14:06:42

+0

查看更新。最好問一個單獨的問題輸出數據或更好的仍然在這裏搜索... – YXD 2013-04-08 14:13:47

+0

http://stackoverflow.com/questions/899103/python-write-a-list-to-a-file – YXD 2013-04-08 14:14:33

0
def gen_vals(data): 
    for i in xrange(len(data["interactions"])): 
     for j in data["interactions"][i]["input"]: 
      yield (j[4], j[9]) 

這是一個發電機,可以這樣使用:

vals = [x for x in gen_vals(data)]