json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 出现原因及解决方案

出现原因

读错误返回码可知,json的key需要双引号"key",此时大概率读入的json文件的key用的时单引号'key'

#error exp 错误示范
{'k1':v1,'k2':v2}
#right exp 正确示范
{"k1":v1,"k2":v2}

在python中,字典dict()的key用单引号或者双引号都ok,不会报错,但是在json文件中会对key的引号进行检查,以保证在跨语言读取时的鲁棒性。

解决方案

此时有以下解决方案

#error exp 错误示范
with open('xxx.json','w') as fw:
	fw.writelines(str(dict()))

#right exp 正确做法
with open('xxx.json','w') as fw:
	fw.writelines(json.dumps(dict()))
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 4 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 6 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐