json.dumps()不工作

json.dumps()不工作,json,python-2.7,Json,Python 2.7,上面的代码不会将数据转储到“file.json”文件中。 当我在json.dumps()之前写入print时,数据就会打印到屏幕上。 但它不会被转储到文件中 该文件已创建,但打开时(使用记事本),什么都没有。 为什么? 如何纠正 您需要使用json.dumpjson.dumps返回一个字符串,它不会写入文件描述符。这不是json.dumps()的工作方式json.dumps()返回一个字符串,然后必须使用f.write()将其写入文件。像这样: import json def json_ser

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

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


如何纠正

您需要使用
json.dump
json.dumps
返回一个字符串,它不会写入文件描述符。

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

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")
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_str = json.dumps({'profile_info': prof_info})
    f.write(json_str)
简单地说

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

还要检查输出文件路径是否为相对路径

import json

my_list = range(1,10) # a list from 1 to 10

with open('theJsonFile.json', 'w') as file_descriptor:

         json.dump(my_list, file_descriptor)