简体   繁体   English

为什么 python 会生成一个字符串 json 文件?

[英]Why does python generate a string json file?

I would like to generate a json file from data retrieved in an api request and another json file.我想从 api 请求和另一个 json 文件中检索到的数据生成 json 文件。 The problem is that in my generated json file, the braces are surrounded by double quotes and I also have "\n" and "\r" everywhere.问题是在我生成的 json 文件中,大括号被双引号包围,而且我到处都有“\n”和“\r”。 Do you have a solution to generate a json file correctly?您是否有正确生成 json 文件的解决方案?

A piece of my python code:我的一段 python 代码:

def write_json(data, filename='data.json'):
    with open(filename, 'w', encoding='utf-8') as wf:
        json.dump(data, wf, ensure_ascii=False, indent=4)

# JSON file to fetch IDs
with open('sast-projects.json', 'r', encoding='utf-8') as f:
    projects = json.load(f)

with open('data.json') as json_file:
    data = json.load(json_file)
    temp = data['data']
    
    for project in projects:
        result_detail = requests.get(url_detail + str(project['id']), headers=header_detail)
        temp.append(result_detail.text)
        write_json(data)

And an example of my outpout (data.json):我的输出示例(data.json):

{
    "data": [
        "{\r\n  \"id\": 12,\r\n  \"teamId\": 34,\r\n  \"owner\": \"Some text\",\r\n  \"name\": \"Some text\"\r\n    }\r\n  ]\r\n}",
        "{\r\n  \"id\": 98,\r\n  \"teamId\": 65,\r\n  \"owner\": \"Some text\",\r\n  \"name\": \"Some text\"\r\n    }\r\n  ]\r\n}"
    ]
}

Change result_detail.text to result_detail.json() .将 result_detail.text 更改为result_detail.text result_detail.json() You're trying to store the raw json string instead of a json object, which is causing double encoding issues.您正在尝试存储原始 json 字符串而不是 json object,这会导致双重编码问题。

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

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