json.dumps() 不工作

标签 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")

上面的代码不会将数据转储到“file.json”文件中。
当我写 print之前 json.dumps() ,然后将数据打印在屏幕上。
但它不会转储到文件中。

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

如何纠正?

最佳答案

不是这样json.dumps()作品。 json.dumps()返回一个字符串,然后您必须使用 f.write() 将其写入文件.像这样:

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

或者,只需使用 json.dump() ,它的存在正是为了将 JSON 数据转储到文件描述符中。
with open(path, 'w') as f:
    json.dump({'profile_info': prof_info}, f)

关于json.dumps() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21453117/

相关文章:

java - 从 API 读取数据

python-2.7 - 在 Pelican 中安装第三方 Markdown 扩展

windows - 如何使用 Python 2.7.3 更改 Windows 背景

python - 有什么方法可以限制子类继承其父类的某些方法吗?

javascript - 如何使用 Express Node.JS 将 JSON 文件属性值大写?

PHP查询转json

json - 如何修剪 Postgres 的 JSON 数据类型中的空格?

python - 解析JSON文件中的坐标值并提取其对应的属性值

python - 如何维护 PhotoImage 对象的多个引用

python - 在 python 中创建 cd 式结构的奇怪问题