【问题标题】:How to write a Python dictionary in JSON format? [closed]如何以 JSON 格式编写 Python 字典? [关闭]
【发布时间】:2013-07-13 08:19:27
【问题描述】:

我正在尝试以 JSON 格式编写字典,如下所示:

cpu = dict [{'ts':"00:00:00",'values':[3,4,5,67,3,34,2,34]},{'ts':"00:00:11",'values':[2,3,4,5,6,3,4]}]

这样的格式怎么写?

【问题讨论】:

  • dict[...] 无法正常工作,因为dict 是内置类型。

标签: python json python-3.x


【解决方案1】:

有一个内置的 json 模块,可用于将字典转换为 json 格式。

所以:

import json

json.dumps({'a':1,'b':2}) #this will return a string with your dict in json format.

#'{"a": 1, "b": 2}'

这里是a link,如果您想了解有关该模块的更多信息并探索其他功能。

希望有帮助!

【讨论】:

  • 你为什么在调用dumps的结果上调用dumps?如果你这样做是有原因的,如果你解释原因,你的答案会更好。
  • oops.. 抱歉,我复制粘贴代码时出错了,希望没有造成太大困扰!
【解决方案2】:

使用与 Python 捆绑的json module:

import json

json.dumps(cpu)

【讨论】:

  • @tbaror:只是想理解和改进我的答案:你为什么改变你标记为接受的答案?
【解决方案3】:

simplejson(或json),是一个内置的python库,对此非常有用。

>>> d = {'a':1,'b':2,'c':3}
>>> import simplejson

>>> # To get a JSON string representation
>>> simplejson.dumps(d)

>>> # To directly add the JSON data to a file
>>> simplejson.dump(d,open("json_data.txt",'w'))

还有更多有趣的可能性,比如在转储到 JSON 之前对键进行排序:

>>> print(simplejson.dumps({"c": 3, "b": 2, "a": 1}, sort_keys=True))

最新文档的链接 - here。

【讨论】:

  • AFAIK simplejson 是 json 库的一种稍微优化的形式,具有相同的功能集。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2017-03-05
  • 2020-07-18
  • 2018-07-19
  • 1970-01-01
  • 2012-06-24
相关资源
最近更新 更多