json.decoder.JSONDecodeError:尝试解析JSON字符串时出现无效控制字符错误。
import json
import pprint
json_data = None
with open("C:\\Users\\75\\OneDrive\\PROJECT P1\\Work_1.0\\CBP\\server.txt", 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
f.close()
jsonString = json.dumps(json_data,default = str)
jsonFile = open("converted.json", "w")
jsonFile.write(jsonString)
jsonFile.close()
要求是从文本文件导入未格式化的转储数据,并转换为JSON,然后使用python将其写入.json文件
获取以下错误
Traceback (most recent call last):
File "C:\\Users\\75\\OneDrive\\PROJECT P1\\Work_1.0\\CBP\\server.txt", line 11, in <module>
json_data = json.loads(data)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 124 (char 123)
1条答案
按热度按时间abithluo1#
为了解决这个错误,在调用json.loads()时将strict关键字参数设置为False。
所以你代码应该如下: