python - 用 requests.get 编写一个 get json 函数,而 json 文件是单引号的
问题描述
我正在编写一个使用 requests.get 获取 json 原始文件的函数,将其写入文件,将所有单引号转换为双引号(api 输出带有单引号的 json 文件),将其写入文件,然后返回数据。我写的那个根本行不通,如果行了,两次写入和读取物理文件仍然很草率。有没有可能提高效率的方法?
def getInfo(type):
PARAMS = {
'token': '',
'type': type, }
URL = urljoin(host, '/data')
response = requests.get(url=URL, params=PARAMS).json()
try:
os.mkdir('json')
except:
pass
jsonFile = open(os.path.join('json', type + ".json"),
"w").write(str(response))
filer = open(os.path.join('json', type + '.json'), 'r')
file = open(os.path.join('json', type + '.json'), 'w')
for line in filer:
# read replace the string and write to output file
file.write(line.replace("'", '"'))
file.close()
jsonFile = open(os.path.join('json', type + ".json"),
"w").write(str(file))
with open(os.path.join('json', type + ".json")) as f:
data = json.loads(f.read())
return data
例子.json
[{'api_member_id': 14171432, 'api_id': 1, 'api_name': 'No.1', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [341, 38, 317, 345, 145, 50]}, {'api_member_id': 14171432, 'api_id': 2, 'api_name': 'No.2', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [13, 19, 118, 36, -1, -1]}, {'api_member_id': 14171432, 'api_id': 3, 'api_name': 'No.3', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [58, 167, 14, 146, -1, -1]}, {'api_member_id': 14171432, 'api_id': 4, 'api_name': 'No.4', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [-1, -1, -1, -1, -1, -1]}]
解决方案
谢谢@Epsi95
def getInfo(type, debug=False):
PARAMS = {
'token': '',
'type': type}
URL = urljoin(host, '/data')
response = requests.get(url=URL, params=PARAMS).text.replace("'", '"')
if debug is True:
mkdir('json')
jsonFile = open(os.path.join('json', type + ".json"),
"w", encoding='utf-8').write(str(response))
return json.loads(response)```
推荐阅读
- reactjs - 尽管我通过了第二个参数,但 React Hook useEffect() 连续运行
- python - 如何在这个 pyqt5 窗口中使用 while 循环
- c++ - C++ std::atomic 在程序员级别有什么保证?
- javascript - 如何从javascript中的模板构建html?
- java - 图像未显示在 Html 页面上
- reactjs - react native忽略android导航栏
- angular - angular-6-datatable 多选行
- php - Laravel - 如何为员工主管创建分层下拉列表
- python - 将函数应用于 a 中的所有条目;分隔列(地图?熊猫?)
- javascript - Chrome 网络选项卡中瀑布列中的内容下载时间不一致