将Json Dictionary对象转换为Python dicitonary

时间:2016-01-24 03:52:17

标签: python json dictionary

我有一个带有对象字典的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}

我想将它转换为格式相同的python字典

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

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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}
]