实现的效果
def send_requests(method, url, request_data, headers=None):
"""
:param method:
:param url:
:param request_data:
:param headers:
:return: 响应对象
"""
print("发起HTTP请求")
# 将请求数据转换成字典对象。
print(f"请求头为:{headers}")
print("请求方法为:{}".format(method))
print("请求url为:{}".format(url))
# 替换双引号是为了方便在第三方工具里校验数据
request_data_info = str(request_data).replace("'", '"')
print(f"请求数据为:{request_data_info}")
method = str(method).lower() # 小写处理
if method == "get":
# request_date为字典
request_result = requests.get(url=url, params=request_data, headers=headers)
elif method == "post_params":
# 处理post不支持json的情况,request_date为字典
request_result = requests.post(url=url, params=request_data, headers=headers)
else:
# post request_date为json
request_result = requests.post(url=url, json=request_data, headers=headers)
# 返回响应对象
return request_result
weather_api = {"method": "get",
"url": "https://v0.yiketianqi.com/free/day",
"params": {
"appid": "83791773",
"appsecret": "a8UpKWz2",
"city": "武汉"
}}
print(send_requests(weather_api["method"], weather_api["url"], weather_api["params"]).json())
json_str = """{"appid": "83791773", "appsecret": "a8UpK23Wz2", "city": "武汉"}"""
# 符合条件的字符转dict
print(type(eval(json_str)))
json_str = {"appid": "83791773", "appsecret": "a8UpK312Wz2", "city": "武汉"}
# dict转json
json_str = json.dumps(json_str)
print(json_str, type(json_str))
# 字符转json对象
json_str = """{"appid": "83791773", "appsecret": "a8UpK213Wz2", "city": "武汉"}"""
json_str = json.loads(json_str)
print(json_str)
pip install jsonpath
jsonStr = {'nums': 2, 'cityid': '101200101', 'city': '武汉', 'date': '2022-06-30', 'week': '星期四',
'update_time': '10:22',
'wea': '晴', 'wea_img': 'qing', 'tem': '31', 'tem_day': '34', 'tem_night': '26', 'win': '东南风',
'win_speed': '1级', 'win_meter': '5km/h', 'air': '82', 'pressure': '1001', 'humidity': '69%',
"test1": {'city': '武汉2'}}
def jsonpath_match_by_key(json, key_name, index):
"""
匹配json中所有的键值对,返回指定索引的key的value
:param json: json
:param key_name: key
:param index: 索引
:return:
"""
bool_root_match = jsonpath.jsonpath(json, f"$.{key_name}")
match_list = []
if bool_root_match:
match_list.append({key_name: bool_root_match[0]})
match_list2 = jsonpath.jsonpath(json, f"$..[?(@.{key_name})]")
if match_list2:
match_list = match_list + match_list2
return match_list[index].get(key_name)
print(jsonpath_match_by_key(jsonStr, "city", 1))
这里主要使用的jsonpath的过滤表达式实现,详情可以自行百度
pip install jsonpath_ng
jsonStr = {'nums': 2, 'cityid': '101200101', 'city': '武汉', 'date': '2022-06-30', 'week': '星期四',
'update_time': '10:22',
'wea': '晴', 'wea_img': 'qing', 'tem': '31', 'tem_day': '34', 'tem_night': '26', 'win': '东南风',
'win_speed': '1级', 'win_meter': '5km/h', 'air': '82', 'pressure': '1001', 'humidity': '69%',
"test1": {'city': '武汉2'}}
def alter_by_jsonpath(json, json_path: str, alter_value):
"""根据jsonpath匹配并修改json的值"""
jsonpath_expr = parse(json_path)
jsonpath_expr.find(json)
jsonpath_expr.update(json, alter_value)
return json
print(alter_by_jsonpath(jsonStr, "$.test1.city", "*****AAA******"))
json的字符串无法使用eval转dict,一般是因为json中有几个特殊的值false,true,null
而在python中这几个都是大写的,null对应的是None
json_str = """{"appid": false, "appsecret": true, "city": null}"""
def handle_string_fit_eval(string) -> str:
"""
处理json字符使满足eval()
:param string:
:return:
"""
return str(string).replace('false', 'False').replace('true', 'True').replace(
'null', 'None')
sss = eval(handle_string_fit_eval(json_str))
print(sss)
print(type(sss))