Python - json vs dictionary dict

Both JSON and dictionaries in Python are data serialization formats, and both of them can convert data into strings for storage or transmission. While they have some similarities, there are also many differences.

dictionary

A dictionary is a data type in Python that is a collection of key-value pairs. Each key corresponds to a value, and the value can be accessed through the key. Keys in a dictionary must be unique, while values ​​can be repeated. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

JSON

JSON is a lightweight data-interchange format based on the JavaScript object representation schema. JSON uses key-value pairs similar to Python dictionaries to represent data, but requires that the key names must be enclosed in double quotes, and the key names must be strings. For example:

{  
    "name": "John",  
    "age": 30,  
    "city": "New York"  
}

The relationship between dictionaries and JSON

While dictionaries and JSON are somewhat similar, there are also many differences. JSON is a data interchange format, while dictionary is a data type of Python. JSON is more canonical and strict, while dictionaries are more flexible and easy to use.

A dictionary can be converted to a JSON string, and a JSON string can be converted to a Python object. For example:

import json  
  
data = {  
    "name": "John",  
    "age": 30,  
    "city": "New York"  
}  
  
# 将字典转换为JSON字符串  
json_str = json.dumps(data)  
print(json_str)  
  
# 将JSON字符串转换为Python对象  
data_from_json = json.loads(json_str)  
print(data_from_json)

output:

{"name": "John", "age": 30, "city": "New York"}  
{'name': 'John', 'age': 30, 'city': 'New York'}

Note that when converting a dictionary to a JSON string, the json.dumps() method needs to be used. When converting a JSON string to a Python object, you need to use the json.loads() method.

JSON configuration

The json module in Python is built-in, no need to install any third-party library. However, if you need to customize the JSON generation and parsing process, you can use the json.JSONEncoder and json.JSONDecoder classes to customize the serialization and deserialization process. At the same time, you can also use the json.JSONOption class to configure the JSON generation and parsing process, such as setting the indentation spacing or date and time format.

JSON supports only a subset of data types, such as strings, numbers, objects, arrays, and booleans. If you need to support other data types, such as datetime or custom objects, you need to customize the serialization and deserialization process.

Guess you like

Origin blog.csdn.net/weixin_44697721/article/details/131931370