我正在从 API 中提取 json 数据。我的脚本将存储此数据并将有关此数据的信息添加到字典中。
为了存储 json 数据,我打算使用:
with open('data.json', 'w') as f:
json.dump(data, f)
什么是存储字典的合适方法?将 dict 转换为 json 格式是否合适
json_str = json.dumps(dict1)
和上面一样保存?
最佳答案
您应该将 JSON 数据保存在 Python list
或 dict
中,具体取决于您的 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/