文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
下面进入讲解部分,文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
1、先将json解析为python对象文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
所以,我们想得到字典中的某一个值,是不是只需要确定它的键就好了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64887.html
若想提取出来'beijing',是不是只需要找到他的键--'spell', 然而'spell'没有对应的键,但是我们注意到'spell'所在的这个字典(上图绿框),是一个列表的第一个元素,假设这个列表为a,那么a[0]就是绿框所示的东西 而这个列表对应的键又是'citylist','citylist'所在的这个字典又是我们解析出的json对象,这就到源头了。
import json
import pandas as pd
with open(r'subway.json', 'r', encoding='utf-8') as f:
response = json.load(f)
# 获取键: citylist的内容,其内容为一个列表
citylist_content = response['citylist']
# 获取列表中第一个元素,该元素即为上图绿框的内容
first_element = citylist_content[0]
# 获取键: spell 对应的内容
spell_content = first_element['spell']
print(spell_content)
# 打印出结果为: beijing
import json
import pandas as pd
# 创建一个字典
data = {
"spell": [], # 用来存储json中spell对应的数据
"adcode": [], # 用来存储json中adcode对应的数据
"cityname": [] # 用来存储json中cityname对应的数据
}
with open(r'subway.json', 'r', encoding='utf-8') as f:
response = json.load(f)['citylist']
for res in response:
data['spell'].append(res['spell'])
data['adcode'].append(res['adcode'])
data['cityname'].append(res['cityname'])
pd.DataFrame(data)
import json
import pandas as pd
with open(r'subway.json', 'r', encoding='utf-8') as f:
response = json.load(f)['citylist']
# 创建字典
data = {key: [] for key in response[0].keys()}
for res in response:
for key in data.keys():
data[key].append(res[key]) # 写入数据
pd.DataFrame(data)