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

What is recommended way to store dictionaries and json file type in python

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

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

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

存储字典的合适方法是什么?使用

将字典转换为 json 格式是否合适
json_str = json.dumps(dict1)

然后按照上面的方法保存?

通常我使用字典来存储数据,转换from/to JSON 仅用于通过网络传输数据。 JSON 不是 Python 的原生类型,因此最好使用原生 Python 类型。

您应该将 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 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 数组结构提供的订单信息。