在Python中将 JSON 转换为字典
JSON 代表 JavaScript 对象表示法。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 json 的内置包支持 JSON。要使用此功能,我们在Python脚本中导入 json 包。 JSON中的文本是通过quoted-string完成的,该字符串包含{}内键值映射中的值。它类似于Python中的字典。
使用的函数:
- json.load(): json.loads()函数存在于Python内置的“json”模块中。该函数用于解析 JSON字符串。
Syntax: json.load(file_name)
Parameter: It takes JSON file as the parameter.
Return type: It returns the python dictionary object.
示例 1:假设 JSON 文件如下所示:
我们想将此文件的内容转换为Python字典。下面是实现。
Python3
# Python program to demonstrate
# Conversion of JSON data to
# dictionary
# importing the module
import json
# Opening JSON file
with open('data.json') as json_file:
data = json.load(json_file)
# Print the type of data variable
print("Type:", type(data))
# Print the data of dictionary
print("\nPeople1:", data['people1'])
print("\nPeople2:", data['people2'])
Python3
# Python program to demonstrate
# Conversion of JSON data to
# dictionary
# importing the module
import json
# Opening JSON file
with open('data.json') as json_file:
data = json.load(json_file)
# for reading nested data [0] represents
# the index value of the list
print(data['people1'][0])
# for printing the key-value pair of
# nested dictionary for loop can be used
print("\nPrinting nested dictionary as a key-value pair\n")
for i in data['people1']:
print("Name:", i['name'])
print("Website:", i['website'])
print("From:", i['from'])
print()
输出 :
示例 2:读取嵌套数据
在上面的 JSON 文件中,第一个键 people1 中有一个嵌套字典。下面是读取嵌套数据的实现。
Python3
# Python program to demonstrate
# Conversion of JSON data to
# dictionary
# importing the module
import json
# Opening JSON file
with open('data.json') as json_file:
data = json.load(json_file)
# for reading nested data [0] represents
# the index value of the list
print(data['people1'][0])
# for printing the key-value pair of
# nested dictionary for loop can be used
print("\nPrinting nested dictionary as a key-value pair\n")
for i in data['people1']:
print("Name:", i['name'])
print("Website:", i['website'])
print("From:", i['from'])
print()
输出 :