json.dumps()无效

use*_*411 4 json python-2.7

import json

def json_serialize(name, ftype, path):

        prof_info = []

        prof_info.append({
            'profile_name': name,
            'filter_type': ftype
        })

        with open(path, "w") as f:
            json.dumps({'profile_info': prof_info}, f)

json_serialize(profile_name, filter_type, "/home/file.json")
Run Code Online (Sandbox Code Playgroud)

上面的代码不会将数据转储到"file.json"文件中.当我print以前写的时候json.dumps(),数据会在屏幕上打印出来.但它不会被转储到文件中.

文件被创建但在打开它时(使用记事本),什么都没有.为什么?

怎么纠正呢?

sen*_*hin 6

这不是多么json.dumps()有效.json.dumps()返回一个字符串,然后您必须使用该字符串写入该文件f.write().像这样:

with open(path, 'w') as f:
    json_str = json.dumps({'profile_info': prof_info})
    f.write(json_str)
Run Code Online (Sandbox Code Playgroud)

或者,只是使用json.dump(),它恰好是为了将JSON数据转储到文件描述符中而存在的.

with open(path, 'w') as f:
    json.dump({'profile_info': prof_info}, f)
Run Code Online (Sandbox Code Playgroud)