Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JSON字典理解输出(使用Python)转换为有效的JSON格式_Json_Python 3.x - Fatal编程技术网

将JSON字典理解输出(使用Python)转换为有效的JSON格式

将JSON字典理解输出(使用Python)转换为有效的JSON格式,json,python-3.x,Json,Python 3.x,下面是我的Python代码的一部分,它打印JSON数据(来自“unique”变量)并将其保存在文件中: import json json_final = open('config/php_conf/user_data.json','r') json_data_edit = json_final.read() obj1 = json.loads(json_data_edit) #unique variable contains only JSON objects with the same

下面是我的Python代码的一部分,它打印JSON数据(来自“unique”变量)并将其保存在文件中:

import json

json_final = open('config/php_conf/user_data.json','r')
json_data_edit = json_final.read()

obj1 = json.loads(json_data_edit)

#unique variable contains only JSON objects with the same user_agent value
unique = {each['user_agent']: each for each in obj1}.values()

# write to new json file
with open('config/php_conf/user_data.json', "w") as nf:
    for js in unique.values():
    nf.write(json.dumps(js))
    nf.write('\n')
没有错误,但这里是输出,这是一种错误的JSON格式,将来无法使用:

输出:

{"browser": "Mozilla", "browser_version": "5.0 (X11)", "operating_system": "Linux x86_64", "user_agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0", "cookie": "", "java_enabled": "function javaEnabled() {    [native code]}", "screen_resolution": "1920x1080"}
{"browser": "Chrome", "browser_version": "6.9 (X11)", "operating_system": "Windows 10", "user_agent": "Different", "cookie": "", "java_enabled": "function javaEnabled() {    [native code]}", "screen_resolution": "1920x1080"}

问题在于unique变量,它以这种格式保存输出,但这不是我需要的

我期望的结果是:

[
    {
        "browser": "Mozilla",
        "browser_version": "5.0 (X11)",
        "operating_system": "Linux x86_64",
        "user_agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
        "cookie": "",
        "java_enabled": "function javaEnabled() {    [native code]}",
        "screen_resolution": "1920x1080"
    },
    {
        "browser": "Chrome",
        "browser_version": "6.9 (X11)",
        "operating_system": "Windows 10",
        "user_agent": "Different",
        "cookie": "",
        "java_enabled": "function javaEnabled() {    [native code]}",
        "screen_resolution": "1920x1080"
    }
]  
问题: 如何重新描述unique变量以执行相同的功能(仅使用相同的用户代理保存JSON对象),但以有效的JSON格式打印,而不是我之前显示的格式