2016-01-24 23 views
-1

我有一個JSON文件與字典一樣的物體轉換Json的字典對象到Python dicitonary

{"d1a": 91, "d1b": 2, "d1c": 1, "d1d": 5, "d1e": 7, "d1f": 77, "d1e": 999} 
{"d2a": 1, "d2b": 2, "d2c": 3, "d2d": 4, "d2e": 5, "d2f": 6, "d2e": 7} 
{"d3a": 1, "d3b": 2, "d3c": 3, "d3d": 4, "d3e": 5, "d3f": 6, "d3e": 7} 

我打算將它轉換成一個Python字典格式相同

with open(myfile.json, 'r') as myfile: 
# not sure how the conversion will start 

回答

1

如果這是怎麼了文件內容看起來像,它不是一個有效的JSON作爲一個整體,但每一行都是。

您可以通過線讀取文件線路和呼叫json.loads()

import json 

with open(myfile.json, 'r') as myfile: 
    for line in myfile: 
     print(json.loads(line)) 

而且你可以有一個字典列表,如果你會使用list comprehension

objs = [json.loads(line) for line in myfile] 

你也可以如果您將[]包含在內容中並在每行末尾加上逗號,請撥打loads()一次:

with open("test.json") as myfile: 
    data = "[" + ",".join(myfile.readlines()) + "]" 
    print(json.loads(data)) 
+0

的OBJ文件= [將在MYFILE線json.loads(線),似乎在JSON返回兩個條目,而不是原來的3文件 – jumpman8947

+0

對不起,我的代碼中有一個額外的循環,它取出了一行。 – jumpman8947

0

如果你還沒有,你需要

import json 

然後,

with open(myfile.json, 'r') as file: 
    data = json.load(file) 

而且,你有沒有包含有效的JSON。你可以用你所擁有的在一個數組,使其正常解析:

[ 
    {"d1a": 91, "d1b": 2, "d1c": 1, "d1d": 5, "d1e": 7, "d1f": 77, "d1e": 999}, 
    {"d2a": 1, "d2b": 2, "d2c": 3, "d2d": 4, "d2e": 5, "d2f": 6, "d2e": 7}, 
    {"d3a": 1, "d3b": 2, "d3c": 3, "d3d": 4, "d3e": 5, "d3f": 6, "d3e": 7} 
]