2016-01-24 85 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} 
]