简体   繁体   English

Python 3:如何将文件json读入字典列表?

[英]Python 3: How to read file json into list of dictionary?

I have file with Json format: 我有Json格式的文件:

{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}

When i use following code, it show an error: 当我使用以下代码时,它显示一个错误:

    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)

with open('E:/list.txt','r') as target:
        my_list = json.load(target)

How to convert content of my file into list of dictionary ? 如何将我的文件内容转换成字典列表? Thank you 谢谢

Your file is not a JSON , its a list of JSON . 您的文件是不是一个JSON ,它是一个列表JSON

with open(filec , 'r') as f:
    list = list(map(json.loads, f))

It's not loading your content basically because it's not a valid json format, try this script: 因为它不是有效的json格式,所以基本上不会加载您的内容,请尝试以下脚本:

import json

try:
    file_content = """{"uid": 2, "user": 1}
    {"uid": 2, "user": 1}
    {"uid": 2, "user": 1}"""

    json.loads(file)
except Exception as e:
    print("This is not JSON!")

print('-' * 80)
file_content = """[{"uid": 2, "user": 1},
{"uid": 2, "user": 1},
{"uid": 2, "user": 1}]"""

print(json.loads(file_content))

The result will be: 结果将是:

This is not JSON!
--------------------------------------------------------------------------------
[{'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}]

Proving that if if you wrap your dictionary into brackets and separate the items with commas the json will be parsed correctly 证明如果将字典包装在方括号中并用逗号分隔项目,则json将被正确解析

Of course, If you don't want to tweak your file at all, you can do something like this to create your output: 当然,如果您根本不想调整文件,则可以执行以下操作来创建输出:

import json

file_content = """{"uid": 2, "user": 1}


{"uid": 2, "user": 1}


{"uid": 2, "user": 1}

"""

output = [json.loads(line)
          for line in file_content.split("\n") if line.strip() != ""]
print(output)

You'll have to iterate, because json.load won't do that automatically. 您必须进行迭代,因为json.load不会自动执行该操作。
So should have something like this 所以应该有这样的东西

for line in file:
    json_obj = json.loads(line)
    my_list.append(json_obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM