Python执行cURL传JSON文件报错,如何解决并保存结果为文本?
问题原因
- 载荷构造错误:原代码直接将本地文件路径作为请求体发送,未读取JSON文件的实际内容,服务端收到非法字符串后触发JSON解析错误
- 请求头配置错误:未指定
Content-Type: application/json请求头,requests的data参数默认按表单格式编码内容,不符合接口要求
修正方案
完整可运行代码
import requests import json # 接口地址,请替换xxxx为你的实际API密钥 url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx" # 本地JSON文件路径 json_file = r"C:\Users\Desktop\myfile.json" # 结果保存路径 save_path = r"C:\Users\Desktop\response_result.txt" # 读取本地JSON文件内容 with open(json_file, "r", encoding="utf-8") as f: payload = json.load(f) # 发送POST请求,使用json参数会自动添加application/json请求头 response = requests.post(url, json=payload) # 保存返回结果到本地文本文件 with open(save_path, "w", encoding="utf-8") as f: f.write(response.text) # 控制台打印结果用于调试 print("请求完成,结果已保存到:", save_path) print("响应内容:\n", response.text)
可选写法(直接发送JSON字符串)
如果不需要对JSON内容做处理,也可以直接读取文件字符串发送,和原curl命令逻辑完全一致:
import requests url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx" json_file = r"C:\Users\Desktop\myfile.json" save_path = r"C:\Users\Desktop\response_result.txt" with open(json_file, "r", encoding="utf-8") as f: json_str = f.read() headers = {"Content-Type": "application/json"} response = requests.post(url, data=json_str, headers=headers) with open(save_path, "w", encoding="utf-8") as f: f.write(response.text)
内容的提问来源于stack exchange,提问作者codeheadache
相关产品推荐
相关产品推荐

