I'm trying to write my first json file. But for some reason, it won't actually write the file. I know it's doing something because after running dumps, any random text I put in the file, is erased, but there is nothing in its place. Needless to say but the load part throws and error because there is nothing there. Shouldn't this add all of the json text to the file?

from json import dumps, load
n = [1, 2, 3]
s = ["a", "b" , "c"]
x = 0
y = 0

with open("text", "r") as file:
    print(file.readlines())
with open("text", "w") as file:
    dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
file.close()

with open("text") as file:
    result = load(file)
file.close()
print (type(result))
print (result.keys())
print (result)

推荐答案

You can use json.dump() method:

with open("text", "w") as outfile:
    json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)

Json相关问答推荐

最新版本的Deneb在数据溢出时不支持滚动

在Reaction中从JSON文件中筛选数组

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

如何使用模式注册中心创建从主题中取消本地化的ks qlDB表?

jq :遍历 json 并在键存在时检索集合

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

JOLT JSON 将值从一对多转换为一对一

将 json 文件转换为 json 对象会打乱对象的顺序

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

如何实现一个通用的 serde_json::from_str

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

如何在 wso2 中组合 2 个 json 有效负载?

将 JSON 读取到 pandas 数据框 - ValueError:将 dicts 与非系列混合可能会导致排序不明确

Spring MVC 4:application/json内容类型设置不正确

如何使用 jq 将 JSON 对象流转换为数组

Java JSON 序列化 - 最佳实践

十六进制格式可以与 JSON 文件一起使用吗?如果是这样,怎么做?

Jsonpath 与 Jackson 或 Gson

如何创建 JSON 对象 Node.js

从 Json 对象 Android 中获取字符串值