在 Python 中,JSON 格式和字典都是常见的数据结构。有时我们需要将一个字典转换为 JSON,或者将 JSON 转换为字典,以便于数据的传输、存储和处理。
下面是比较 Python 中的 JSON 和字典,并将键值对放入 JSON 的方式:
import json
# 1. 将字典转换为 JSON
dict_data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(dict_data)
print(json_data)
# 2. 将 JSON 转换为字典
json_data = '{"name": "John", "age": 30, "city": "New York"}'
dict_data = json.loads(json_data)
print(dict_data)
# 3. 比较 JSON 和字典
json_data = '{"name": "John", "age": 30, "city": "New York"}'
dict_data = {
"name": "John",
"age": 30,
"city": "New York"
}
if json_data == json.dumps(dict_data):
print("The JSON data and dictionary data are equal.")
else:
print("The JSON data and dictionary data are not equal.")
# 4. 将键值对放入 JSON
json_data = {}
json_data['name'] = 'John'
json_data['age'] = 30
json_data['city'] = 'New York'
print(json.dumps(json_data))
在上面的代码中,我们使用 json.dumps() 函数将字典转换为 JSON,使用 json.loads() 函数将 JSON 转换为字典。然后,我们可以比较 JSON 和字典是否相等。最后,我们使用键值对的方式将数据放入 JSON 中。
运行上述代码会输出以下结果:
{"name": "John", "age": 30, "city": "New York"}
{'name': 'John', 'age': 30, 'city