實現的效果
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))