对象表示法 或 JSON文件 是一种流行的数据格式,用于在JavaScript编程语言中存储对象。JSON数据格式在开发人员中非常流行,目的是以简单易读的格式存储数据和信息。Python还支持JSON,并提供不同的函数来读取、写入和更改JSON数据和文件。Python字典也被用作本机数据类型,以便以高效的方式存储JSON数据。
Python-json模块
json模块提供了处理json数据和格式所需的方法、结构。这个模块基本上提供了JSON格式的读写、解码或编码方法。为了读取JSON数据文件或JSON数据字符串,这个模块应该像下面这样加载导入。
import json
JSON对象与Python对象转换
JSON使用从JavaScript编程语言派生的不同对象类型。在反序列化期间,所有这些对象类型都应转换为相关的Python类型。此转换在加载JSON数据期间自动完成。下面我们将列出JSON对象类型和相关的Python对象类型。
JSON对象 | PYTHON对象 |
---|---|
对象 | 口述 |
数组 | 列表 |
一串 | str公司 |
无效的 | 没有 |
数字(int) | 内景 |
数字(实数) | 浮动 |
是的 | 是的 |
假 | 假 |
从文件读取(反序列化)JSON数据
JSON最流行的方法之一是从文件中读取JSON。首先,为了读取一个文件,应该用 打开() 方法,打开的文件将提供到 json.load() 方法读取数据,然后反序列化到Python对象中。JSON数据作为字典转换成Python,所有其他内容作为键/值对放在这个字典中。
#Import the Python json module import json#Open the json file which is named file.jsonf = open(file.json)#read and deserialize the json file# The data will be a dictionarydata = json.load(f)#Print the json object which is a dictionary typeprint(data)#close the json filef.close()
从字符串读取(反序列化)JSON数据
json模块还提供了json.loads(),它将加载并反序列化作为字符串的json数据。loads(str)将读取与str一起存储的json数据,并以字典数据类型的形式返回反序列化的方式。
#Import the Python json module
import json
# The p contains the JSON data as stringp = '{"name": "Ali", "languages": ["English", "Turkish"]}'#read and deserialize the json file
# The data will be a dictionary
data = json.load(str)
#Print the json object which is a dictionary type
print(data)
漂亮的打印JSON数据(Python字典)
JSON数据可以用不同的方式表示。默认打印时,JSON数据不会格式化。但是为了增加缩进和排序键的可读性。load()提供 缩进 参数来设置缩进空间计数, 排序u键 参数,用于根据键等对项目进行排序。
#Import the Python json module
import json
# The p contains the JSON data as string
p = '{"name": "Ali", "languages": ["English", "Turkish"]}'
#read and deserialize the json file
# The data will be a dictionary
data = json.load(p , indent=3 , sort_keys=True)
#Print the json object which is a dictionary type
print(data)