python - 在 python 中存储字典和 json 文件类型的推荐方法是什么

标签 python json dictionary formatting storage

我正在从 API 中提取 json 数据。我的脚本将存储此数据并将有关此数据的信息添加到字典中。

为了存储 json 数据,我打算使用:

with open('data.json', 'w') as f:
     json.dump(data, f)

什么是存储字典的合适方法?将 dict 转换为 json 格式是否合适

json_str = json.dumps(dict1)

和上面一样保存?

最佳答案

您应该将 JSON 数据保存在 Python listdict 中,具体取决于您的 JSON 数据的结构。

来自 http://www.json.org/ :

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

json 库通常用于加载 JSON 数据并将其存储在 Python 对象中。但是请注意,如果 JSON 数据类似于 [...] 和 Python < em>dict 如果 JSON 数据类似于 {...}

要读取包含 {...} 的 JSON 文件并将其内容保存到字典数据结构中,请使用:

>>> with open('data.json', 'r') as f:
...   data = json.load(f)
...
>>> type(data)
<type 'dict'>

如果文件包含一个 JSON 列表 [...] 那么:

>>> type(data)
<type 'list'>

从 URL 读取 JSON 数据时类似:

>>> response = urllib2.urlopen(URL)
>>> data = json.load(response)

您总是可以将列表转换为字典,例如:

>>> dataD = dict([i,data[i]] for i in xrange(len(data)))

但是这样做会丢失 JSON 数组结构提供的订单信息。

关于python - 在 python 中存储字典和 json 文件类型的推荐方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35476327/

相关文章:

python - 通过电子邮件请求批准并处理 Python + Django

python - 像 FACS 一样绘制交错的直方图/线

Python MySQL 连接器 : Can't connect to server with SSL

python - 当我们删除一个项目时,字典会调整大小吗?

python - 如何在 Python 中将 str.format() 与字典一起使用?

Python/Django : How to Prepend a # on to all URLS

Php from android in json 未发布到表中,我的代码有问题吗?

javascript - 从 Backbone 集合中检索特定属性的列表

c++ - cJSON - 解析 JSON

Python循环遍历字典以用另一个字典中的值替换键