【Error】 json file 不能读取的解决办法 TypeError: Input string must be text, not bytes

本文分享了在读取JSON文件时遇到TypeError和JSONDecodeError的解决方案,通过使用nestedreplace()去除非法字符,最终成功解析文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最开始是用

with open(path) as f:
	data = json.loads(f)

然后报错TypeError: Input string must be text, not bytes

尝试1,加上解码:

with open(path, encoding='utf-8') as f:
	data = json.loads(f)

仍报错TypeError: Input string must be text, not bytes

尝试2,读取每行:

with open(path, encoding='utf-8') as f:
	data = [json.loads(line) for line in f]

报错JSONDecodeError: Expecting property name enclosed in double quotes or '}'

这时候,我们知道,肯定是json file里面有些“非法”字符需要删除。

最终尝试,使用nested replace去除“非法”字符:

# nested replace() 
with open(gentle_file, encoding='utf-8') as f:
    tmp = f.read().replace('\t','').replace('\n','').replace(',}','}').replace(',]',']')
    data = json.loads(tmp)

成功!

========================================================================================================== test session starts =========================================================================================================== platform win32 -- Python 3.7.3, pytest-7.4.4, pluggy-1.2.0 -- d:\python\python.exe cachedir: .pytest_cache metadata: {'Python': '3.7.3', 'Platform': 'Windows-10-10.0.22621-SP0', 'Packages': {'pytest': '7.4.4', 'pluggy': '1.2.0'}, 'Plugins': {'allure-pytest': '2.14.3', 'html': '3.2.0', 'metadata': '3.0.0', 'ordering': '0.6', 'rerunfailures': '13.0'}} rootdir: D:\pythonProject\接口自动化练习 configfile: pytest.ini testpaths: ./test_moudle plugins: allure-pytest-2.14.3, html-3.2.0, metadata-3.0.0, ordering-0.6, rerunfailures-13.0 collecting ... 测试init方法会调用多少次 collected 3 items test_moudle/test_login.py::Test_Home::test_home[Baseinfo] 2025-07-12 21:21:09,686 INFO [root] [test_login.py(test_home:14)] - 开始执行测试用例:test_api_example FAILED test_moudle/test_login.py::Test_Home::test_home[testcase] 2025-07-12 21:21:09,740 INFO [root] [test_login.py(test_home:14)] - 开始执行测试用例:test_api_example FAILED test_moudle/test_employee.py::TestEmployee::test_add_employee[case0] FAILED ================================================================================================================ FAILURES ================================================================================================================ _____________________________________________________________________________________________________ Test_Home.test_home[Baseinfo] ______________________________________________________________________________________________________ self = <test_moudle.test_login.Test_Home object at 0x00000186D452F780>, case = 'Baseinfo' @pytest.mark.parametrize("case", read_yaml("./test_moudle/login.yaml")) @allure.epic("苍穹外卖") @allure.story("登录模块") @allure.severity(allure.severity_level.CRITICAL) def test_home(self, case): logging.info("开始执行测试用例:test_api_example") > allure.dynamic.title(case["testcase"]["title"]) E TypeError: string indices must be integers test_moudle\test_login.py:16: TypeError ----------------------------------------------------------------------------------------------------------- Captured log call ------------------------------------------------------------------------------------------------------------ INFO root:test_login.py:14 开始执行测试用例:test_api_example _____________________________________________________________________________________________________ Test_Home.test_home[testcase] ______________________________________________________________________________________________________ self = <test_moudle.test_login.Test_Home object at 0x00000186D452F9E8>, case = 'testcase' @pytest.mark.parametrize("case", read_yaml("./test_moudle/login.yaml")) @allure.epic("苍穹外卖") @allure.story("登录模块") @allure.severity(allure.severity_level.CRITICAL) def test_home(self, case): logging.info("开始执行测试用例:test_api_example") > allure.dynamic.title(case["testcase"]["title"]) E TypeError: string indices must be integers test_moudle\test_login.py:16: TypeError ----------------------------------------------------------------------------------------------------------- Captured log call ------------------------------------------------------------------------------------------------------------ INFO root:test_login.py:14 开始执行测试用例:test_api_example _________________________________________________________________________________________________ TestEmployee.test_add_employee[case0] __________________________________________________________________________________________________ self = <test_moudle.test_employee.TestEmployee object at 0x00000186D451BDD8> case = {'request': {'data': {'id': 5, 'idNumber': 432502200112033212, 'name': '小样', 'phone': 18707369896, ...}, 'headers': {'...': 'application/json', 'token': ''}, 'method': 'post', 'url': 'http://localhost:8080/admin/employee'}, 't itle': '增加员工'} @pytest.mark.parametrize("case",read_yaml("./test_moudle/employee.yaml")) def test_add_employee(self,case): method=case["request"]["method"] url=case["request"]["url"] data=case["request"]["data"] headers=case["request"]["headers"] > headers["token"]=read_token("token") test_moudle\test_employee.py:16: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ key = 'token' def read_token(key): with open("token.yaml",'r',encoding='UTF-8') as f: value=yaml.safe_load(f) > return value[key] E TypeError: 'NoneType' object is not subscriptable yaml_untils.py:15: TypeError ======================================================================================================== short test summary info ========================================================================================================= FAILED test_moudle/test_login.py::Test_Home::test_home[Baseinfo] - TypeError: string indices must be integers FAILED test_moudle/test_login.py::Test_Home::test_home[testcase] - TypeError: string indices must be integers FAILED test_moudle/test_employee.py::TestEmployee::test_add_employee[case0] - TypeError: 'NoneType' object is not subscriptable =========================================================================================================== 3 failed in 0.22s ============================================================================================================ D:\pythonProject\接口自动化练习>Traceback (most recent call last): 'Traceback' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:/pythonProject/接口自动化练习/yaml_untils.py", line 18, in <module> 命令语法不正确。 D:\pythonProject\接口自动化练习> print(read_yaml("./test_moudle/login.yaml")) 无法初始化设备 PRN D:\pythonProject\接口自动化练习> File "D:/pythonProject/接口自动化练习/yaml_untils.py", line 5, in read_yaml 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> readYaml=yaml.safe_load(f) 'readYaml' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\__init__.py", line 125, in safe_load 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> return load(stream, SafeLoader) 'return' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\__init__.py", line 81, in load 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> return loader.get_single_data() 'return' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\constructor.py", line 49, in get_single_data 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> node = self.get_single_node() 'node' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\composer.py", line 36, in get_single_node 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> document = self.compose_document() 'document' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\composer.py", line 55, in compose_document 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> node = self.compose_node(None, None) 'node' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\composer.py", line 84, in compose_node 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> node = self.compose_mapping_node(anchor) 'node' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\composer.py", line 127, in compose_mapping_node 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> while not self.check_event(MappingEndEvent): 'while' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\parser.py", line 98, in check_event 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> self.current_event = self.state() 'self.current_event' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> File "D:\python\lib\site-packages\yaml\parser.py", line 439, in parse_block_mapping_key 'File' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> "expected <block end>, but found %r" % token.id, token.start_mark) '"expected <block end>, but found %r"' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习>yaml.parser.ParserError: while parsing a block mapping 'yaml.parser.ParserError:' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> in "./test_moudle/login.yaml", line 1, column 1 'in' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习>expected <block end>, but found '-' 系统找不到指定的文件。 D:\pythonProject\接口自动化练习> in "./test_moudle/login.yaml", line 12, column 1 'in' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 D:\pythonProject\接口自动化练习> D:\pythonProject\接口自动化练习>Process finished with exit code 1 'Process' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
最新发布
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值