json.dump() 将类型从 `dict` 更改为 `NoneType`

json.dump() changes the type from `dict` to `NoneType`

我有一个小的 python 程序,用于操作 JSON 文件。我发现当我使用 json.dump() 将操作数据转储回 JSON 文件时,它会变为 <type 'NoneType'>。下面数据的原始类型(json_data的类型)是<type 'dict'>。我将这些 JSON 文档存储在 elasticsearch 中并使用 Kibana4 将其可视化。Kibana4 将新添加的整数字段视为字符串。以前有人遇到过这个问题吗?

import json                                                                                                                                                                                    

fname = "json_data.txt"
with open(fname, 'r+') as f:
    json_data = json.load(f)
    print(type(json_data))
    #Code to add fields to json files.   
    f.seek(0)
    x = json.dump(json_data,f,ensure_ascii=True)
    print(type(x))

json.dump() 没有 return 值。它将 写入 文件,而不是 return 转储对象。

因此,可调用的默认 return 值 None 改为 return。

换句话说,您的代码完全按照您的要求执行:读取 JSON 数据并解析它,结果存储在 json_data 中。然后,您将该 Python 对象写回到文件中。 json.dump() 的 return 值在这里无关紧要,您仍然可以参考 json_data.

如果您想要一个包含 JSON 对象的字符串值,请使用 json.dumps()(注意 s);此 return 是生成的 JSON 字符串,无需写入文件:

fname = "json_data.txt"
with open(fname, 'r') as f:
    json_data = json.load(f)
    print(type(json_data))

json_string = json.dumps(json_data)
print(type(json_string))

我认为 json.dump() 没有 return 值。您是否正在寻找 json.dumps()