说下遇到的问题。
1、返回数据key:value很多时,直接存到txt中后,打开是一整行,不是json格式的可读性很差。
2、服务器返回的数据加了html编码,存在各种特殊&#amqd等类似字符,易读性差。
解决方法:
json.load和json.dumps
json.dumps()函数是将一个Python数据类型列表进行json格式的编码
json.loads()函数是将json格式数据转换为字典
1、将返回的字符串数据存为python识别的json格式,使用json.loads()
2、利用json.dumps方法,将上一步存储的字典数据进行个格式化处理。intent 4表示格式化后,key只前有4个空格,separators标识按照哪些符号进行格式处理
3、json.dumps处理后,通过str转换为字符串,可以写入文本中。
4、这时文本中如果存在服务器进行的html编码内容,import html后,使用unescape()方法将文本中的内容进行html反编码。
f.write(unescape(str(json.dumps(resp_status_dict,indent=4,separators=(',',':')))))
def json_config_write_file(url,filepath):
status = 0
try:
resp_status = requests.get(url,headers=headers)
status = resp_status.status_code
resp_status_dict = json.loads(resp_status.text)
except requests.exceptions.RequestException as e:
print(e)
return "failed,network error"
if status == 200:
with open(filepath,'w',encoding='utf-8') as f:
f.write(unescape(str(json.dumps(resp_status_dict,indent=4,separators=(',',':')))))
return filepath
else:
return "network error"