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

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

相关推荐
前端付豪6 分钟前
AI知识库 + RAG数学解析增强
前端·python·llm
Eanve9 分钟前
python搭建webrtc音视频服务端客户端
python·音视频·webrtc
七夜zippoe12 分钟前
PostgreSQL高级特性在Python中的实战:JSONB、全文搜索、物化视图与分区表深度解析
数据库·python·postgresql·性能优化·分区表
郝学胜-神的一滴15 分钟前
一序平衡,括号归真:单括号匹配算法的优雅美学
java·前端·数据结构·c++·python·算法
清水白石00816 分钟前
Python 方法绑定机制深度解析:bound method、三种方法类型与代码评审实战
开发语言·网络·python
@国境以南,太阳以西20 分钟前
从0实现OnCall基于Python语言框架
开发语言·python
转型AI的宏达23 分钟前
ETF遍历取数模块 金融量化建模 Python
python
weixin_3077791325 分钟前
提升 LLM 输出鲁棒性:使用 json_repair 智能修复非标准 JSON
开发语言·人工智能·算法·json·软件工程
yaoxin52112329 分钟前
352. Java IO API - Java 文件操作:java.io.File 与 java.nio.file 功能对比 - 4
java·python·nio
nananaij32 分钟前
【LeetCode-04 数组异或操作 python解法】
python·算法·leetcode