简体   繁体   English

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

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

I'm pulling json data from an API. 我正在从API中提取json数据。 My script will store this data and add information about this data to a dictionary. 我的脚本将存储此数据并将有关此数据的信息添加到字典中。

To store the json data, i'm planning on using: 要存储json数据,我打算使用:

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

What would be an appropriate way to store the dictionary ? 存储字典的适当方法是什么? Would it be appropriate to convert the dict to json format with 将dict格式转换为json格式是否合适?

json_str = json.dumps(dict1)

and save it in the same way as above ? 并以与上面相同的方式保存它?

You should save JSON data in a Python list or a dict , depending on the structure of your JSON data. 您应该将JSON数据保存在Python listdict ,具体取决于JSON数据的结构。

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

JSON is built on two structures: JSON基于两种结构:

  • 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. 在大多数语言中,这被实现为数组,向量,列表或序列。

The json library is what's commonly used to load JSON data and store it in a Python object. json库通常用于加载JSON数据并将其存储在Python对象中。 Note however that the load method will return (recursively) a Python list if the JSON data is like [...] and a Python dict if the JSON data is like {...} . 但请注意,如果JSON数据类似于[...] ,则load方法将返回(递归地)Python 列表,如果JSON数据类似于{...}则返回Python dict

To read a JSON file containing a {...} and save its content to a dictionary data structure use: 要读取包含{...}的JSON文件并将其内容保存到字典数据结构,请使用:

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

If the file contains a JSON list [...] then: 如果文件包含JSON列表[...]则:

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

Similarly when reading JSON data from a URL: 类似地,当从URL读取JSON数据时:

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

You can always convert a list to a dictionary for example like this: 您始终可以将列表转换为字典,例如:

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

By doing so however you lose the order information provided by the JSON array structure. 但是,这样做会丢失JSON数组结构提供的订单信息。

Usualy i use dicts for storing data, and convert from/to JSON only for transfer data via web. Usualy我使用dicts来存储数据,并且只能通过web转换/到JSON以传输数据。 JSON is not native type for Python, so it would be better to work with native Python types. JSON不是Python的本机类型,因此最好使用本机Python类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM