将Json字典对象转换为Python字典

2024-09-25 06:33:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

Tags: 文件对象json字典myfiled2bd1ad3e
2条回答

如果这是文件内容的原样,那么它作为一个整体不是有效的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))

如果你没有,你需要

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}
]

相关问题 更多 >