Python JSON 转储对象列表。

标签 python json

我有一个字典列表,如何使用 JSON 将其转储为每个字典一行?

我试过:

json.dump( d, open('./testing.json','w'), indent=0)

其中 d 是字典列表。但这会换行每个 (key,value) 对。我希望每本字典都在一行中。我应该怎么做?

谢谢

最佳答案

您可以在将其写出之前将其转换为具有该格式的字符串。这可以通过列表理解和连接的组合来完成:

strs = [json.dumps(innerdict) for innerdict in d]
s = "[%s]" % ",\n".join(strs)
open('./testing.json','w').write(s)

一行:

open('./testing.json','w').write("[%s]" % ",\n ".join(json.dumps(e) for e in d))

或:

open('./testing.json','w').write("[%s]" % ",\n ".join(map(json.dumps, d)))

关于Python JSON 转储对象列表。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667877/

相关文章:

c# - 使用 DataContractJsonSerializer 生成轻量级 JSON

javascript - 使用 Angular js 从 json 数组中删除重复值

javascript - 使用Angular提取特定的Json数据

json - 如何在 elm-core > 5.0.0 的 Json.Decoder 中从 String 转换为 Int

python - 循环 tkinter 列表框

python - 迭代工具 : creating a 2d iterator

python - 文件路径中的转义空间

python - 为什么我在 pip 安装模块时得到这些 "WARNING: Target Directory <directory> already exists."?

python - 为什么我在调用 Google Sheets API 时收到 "Unknown Name..."名称错误?

ajax - Spring框架从3.0.2升级到3.2.0时Spring JSON出现问题