读取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)

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

相关推荐
我不会起名字3229 分钟前
一天一道算法题(29):单调栈
java·数据结构·python·算法·leetcode·golang·单调栈
萧鼎13 分钟前
2026新库实测:sbxloop 1.5.24 让 AI Agent 在 Docker 沙箱中安全自治,告别环境混乱
人工智能·python·开源·开发工具·ai agent
栀椩29 分钟前
CODrone 无人机航拍车辆检测
pytorch·python·yolo
会飞的拖把34 分钟前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python
2601_9622838837 分钟前
如何通过python控制nbiot
python·串口通信·数据传输·nb-iot·at命令
AC赳赳老秦1 小时前
环保监测公开数据应用:OpenClaw 抓取空气与水质公开监测数据,开展区域环境质量趋势分析
大数据·数据库·人工智能·python·php·deepseek·openclaw
RSABLOCKCHAIN1 小时前
打造工业级多智能体量化交易闭环:基于 Alpaca、LangGraph 与双轨执行的智能投资与持仓治理系统
人工智能·python·ai·aigc
用户019027581611 小时前
如何用 Python 做多因子打分选股?
python
烂蜻蜓1 小时前
Flask入门教程(三十一):实用函数与类API——全局工具函数速查
后端·python·flask
晓窗科技1 小时前
AI基座哪家服务好
大数据·人工智能·python