python - 如何从嵌套数组/字典/对象在 python 中生成 json 文件

标签 python json

我需要生成一个像这样的 json 文件:

{
  "age":100,
  "name":"mkyong.com",
  "messages":["msg 1","msg 2","msg 3"]
}

这个文件中的数据应该从不同的地方填充。在 python 中执行此操作的最佳方法是什么?我总是可以写成文本文件(逐个字符)。但我想知道是否有更简洁的方法可以创建数组并使用一些库方法生成这个 json 文件。请提出一个好的解决方案

附言。我是 python 新手

最佳答案

您可以使用 json.dumps()为了那个原因。您可以将字典传递给它,该函数会将其编码为 json。

例子:

import json

# example dictionary that contains data like you want to have in json
dic={'age': 100, 'name': 'mkyong.com', 'messages': ['msg 1', 'msg 2', 'msg 3']}

# get json string from that dictionary
json=json.dumps(dic)
print json

输出:

{"age": 100, "name": "mkyong.com", "messages": ["msg 1", "msg 2", "msg 3"]}

关于python - 如何从嵌套数组/字典/对象在 python 中生成 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329371/

相关文章:

jquery - 在 jquery 中访问 xhr 的 json 响应

php - 使用 php 循环 json 数组

python - 如何在 SciPy 中沿着 3D 样条曲线查找点?

python - 为什么 "if-else-break"在 python 中中断?

python - 断言错误(-215)npoints> = 0,并且从验证码图像中提取字母时出错

python - 子类中返回值的类型提示

json - Serilog/JSNLog .NET Core 记录空 JSON

python - 在 Python 中从 RTSP 流中读取帧

java - Jackson 3.1.1 列表多态类型的子类型异常缺少类型 ID?

sql-server - 将批量 JSON 数据加载到 SQL Server 表中