python解析json字符串步骤
1、先把原始数据转化为json格式
2、把json格式转化为python格式
一、最简易的json格式
import json
information = {
'class': 302,
'name': 'JokerPlus',
'age':20,
'addr':'Made in China'
}
json_data = json.dumps(information) #把information数据写到json文件中
info = json.loads(json_data) #python读取json数据
print("JSON_Data:", json_data) #json数据
print("class: ", info['class']) #提取inform中的class对象
print("name: ", info['name']) #提取inform中的name对象
print("age:",info['age']) #提取inform中的age对象
print("addr:",info['addr']) #提取inform中的addr对象
二、多级json格式数据
import json
information = {
'class': 302,
'name': 'JokerPlus',
'age': 20,
'addr': 'Made in China',
'hobby': ('sing', 'jump', 'rap', 'basketball'),
'results': {'chinese': 95, 'math': 90, 'english': 60},
'historytime': {'time': {'timestamp': 2020, 'datatime': -2000},
'history': {'countrytime': 5000, 'other': 'below 5000'}}
}
json_data = json.dumps(information)
info = json.loads(json_data)
print("JSON_Data:", json_data)
print("class: ", info['class'])
print("name: ", info['name'])
print("age:", info['age'])
print("addr:", info['addr'])
print("hobby:", info['hobby']) # 一级类型
print("results:", info['results']['chinese']) # 二级类型
print("chinesehistory:", info['historytime']['time']['datatime']) # 三级类型
三、实际使用,解析天气信息json
import json
weather = {
"code":1,
"msg":"Sucess",
"counts":29,
"other":{
"cityId":"CH280101",
"cityName":"广州",
"lastUpdate":"2020-06-16 14:14:29",
"tq":"中雨",
"numtq":"08",
"qw":"27",
"numfl":3,
"fl":"5-6级",
"fx":"西风",
"numfx":"6",
"sd":"84%"
}
}
weather_data = json.dumps(weather)
data = json.loads(weather_data)
print("code:",data['code'])
print("信息:",data['msg'])
print("今日剩余次数:",data['counts'])
print("城市ID:",data['other']['cityId'])
print("城市名称:",data['other']['cityName'])
print("更新时间:",data['other']['lastUpdate'])
print("天气现象:",data['other']['tq'])
print("天气现象编码:",data['other']['numtq'])
print("当前气温:",data['other']['qw'])
print("当前风力:",data['other']['fl'])
print("当前风力编码:",data['other']['numfl'])
print("当前风向:",data['other']['fx'])
print("当前风向编码:",data['other']['numfx'])
print("相对湿度:",data['other']['sd'])
四、解析json的其他相关的,后续遇到了再发上来。