读取Json BugFix

遇到的错误如下所示:

bash 复制代码
遇到的错误如下所示:

File ~/miniconda3/lib/python3.9/json/decoder.py:353, in JSONDecoder.raw_decode(self, s, idx)
    344 """Decode a JSON document from ``s`` (a ``str`` beginning with
    345 a JSON document) and return a 2-tuple of the Python
    346 representation and the index in ``s`` where the document ended.
   (...)
    350 
    351 """
    352 try:
--> 353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
    355     raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting property name enclosed in double quotes: line 54022608 column 6 (char 987758592)

网上查询这个错误是JSon里面的双引号搞成了单引号,故作相应的替换;

将单引号替换为双引号,下面为相应的代码:

python 复制代码
# 导入Python的JSON模块,该模块提供了解析JSON的函数  
import json  
  
# 定义要读取的JSON文件的路径  
json_path  = './example.json'  
  
# 使用with语句打开文件,这样可以确保文件在读取后会被正确关闭  
with open(json_path,'r') as f:  
  
    # 使用json模块的load函数从文件中读取JSON数据,并将其解析为Python对象  
    output = json.load(f)  
      
    # 使用json模块的dumps函数将Python对象转换为JSON格式的字符串  
    json_str = json.dumps(output)   
  
    # 使用字符串的replace函数将所有的单引号替换为双引号。这一步其实是不必要的,因为json模块在解析和生成JSON时默认使用双引号。  
    json_str = json_str.replace("'", "\"")  
  
    # 再次使用json模块,这次使用loads函数将修改后的JSON字符串重新解析为Python对象  
    json_obj = json.loads(json_str)   
  
    # 使用with语句打开一个新的文件用于写入,这个文件被命名为'replace.json'  
    with open('./replace.json','w+') as f:  
        # 使用json模块的dump函数将Python对象写入文件,参数indent设置为2表示生成的JSON数据将采用缩进格式,便于阅读  
        json.dump(json_obj, fp=f, indent=2)

水平有限,有问题随时交流~

相关推荐
段一凡-华北理工大学5 小时前
工业智能体:从Codex/Claude到项目实战~系列文章05:从“AI助手“到“工业智能体“:能力跃迁与落地范式
人工智能·python·claude·codex·工业智能体·高炉炼铁智能化
深蓝AI6 小时前
ContextVar 到线程池就丢了?asyncio.to_thread 和 run_in_executor 实测
python
岁月宁静7 小时前
什么是 Agent:从"会聊天"到"会做事"
人工智能·python
岁月宁静7 小时前
AI 应用开发工程师简历怎么写:HR 初筛、技术复筛、面试追问,三道关卡各看什么?
人工智能·python·面试
来让爷抱一个7 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
小肝一下9 小时前
3.基础语法(3)
python
深蓝AI10 小时前
Python 子进程树:父进程被杀后,孙进程为何还在跑?
python
心祭丫丫10 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习
爱你真是太好了10 小时前
Skill 索引瘦身与渐进加载
python
贾公子10 小时前
检测链路的容量规划——用 Little's Law 算清 QPS、并发与积压
后端·python