json文件的读取

📚博客主页:knighthood2001

公众号:认知up吧 (目前正在带领大家一起提升认知,感兴趣可以来围观一下)

🎃知识星球:【认知up吧|成长|副业】介绍
❤️感谢大家点赞👍🏻收藏⭐评论✍🏻,您的三连就是我持续更新的动力❤️
🙏笔者水平有限,欢迎各位大佬指点,相互学习进步!

引言

如果你有这样的一个json文件,保存在2.png.json文件中,我需要将其中的文本text读取出来。并将结果保存在txt文件中,如何操作呢。

json 复制代码
{
  "taskId": 2,
  "ocrResult": [
    {
      "text": "// ocr回调函数,第一个参数是request id,第二个参数是数据,第三个参数是ocrmanage类",
      "location": {
        "left": 3.7124999,
        "top": 1.2375,
        "right": 542.02496,
        "bottom": 16.0875
      },
      "pos": {
        "x": 3.7124999,
        "y": 1.2375
      }
    },
    {
      "text": "intcdecl 0cRReadonPush(int al,int a2,int a3)",
      "location": {
        "left": 3.09375,
        "top": 17.943748,
        "right": 347.7374,
        "bottom": 30.937498
      },
      "pos": {
        "x": 3.09375,
        "y": 17.94375
      }
    }
  ]
}

实现过程

python 复制代码
import json
json_file = r"G:\Desktop\python小项目\调用微信ocr进行识别文字\12.png.json"
save_file = "save.txt"

首先导入json库以及定义好读取json以及保存txt文件的路径。

python 复制代码
# 打开 JSON 文件
with open(json_file, 'r', encoding='utf-8') as file:
    # 从文件中加载 JSON 数据
    data = json.load(file)

接下来就是加载json数据,其中'r'表示read读取,此外,encoding='utf-8'必须需要,否则对中文就会有如下报错。

UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 71: illegal multibyte sequence

可以打印一下数据以及数据类型:

python 复制代码
# 打印读取的 JSON 数据
print(data)
print(type(data))

可以看到这时候的数据类型就是字典,对于字典就可以通过键值对进行查找。

如果你需要打印text内容

python 复制代码
    # 提取每个对象的 text 字段
    for item in data['ocrResult']:
        print(item['text'])

如果需要将其保存到txt文件中,你可以通过下面的代码实现

python 复制代码
with open(save_file, 'w', encoding='utf-8') as f:
    # 提取每个对象的 text 字段
    for item in data['ocrResult']:
        print(item['text'])
        f.write(item['text'] + '\n')
        # f.write(item['text'])

首先这里的'w'指的是write写入,encoding='utf-8'这里也不能省,否则写入中文的时候会出现乱码。

然后我们先将item进入到json文件中的'ocrResult'中,然后我们可以通过item['text']获取到对应的文本。

最后通过write写入文本到txt中,这里注意一下,如果不手动添加'\n',则只是保存文本到同一行中。如果需要分行保存,则需要添加一下。

封装一下

这里考虑到有时候我们需要将保存的内容分行保存,有时候又不需要分行保存,所以这里我通过设置一个mode进行分模式保存。

python 复制代码
def save_text(json_file, save_file, mode=1):
    # 打开 JSON 文件
    with open(json_file, 'r', encoding='utf-8') as file:
        # 从文件中加载 JSON 数据
        data = json.load(file)
    # 换行保存
    if mode == 1:
        with open(save_file, 'w', encoding='utf-8') as f:
            # 提取每个对象的 text 字段
            for item in data['ocrResult']:
                print(item['text'])
                f.write(item['text'] + '\n')
    if mode == 2:
        with open(save_file, 'w', encoding='utf-8') as f:
            # 提取每个对象的 text 字段
            for item in data['ocrResult']:
                print(item['text'])
                f.write(item['text'])
python 复制代码
save_text(json_file, save_file, mode=2)

此时你可以通过选择mode的参数进行选择是否按行保存,默认按行保存。

全部代码

python 复制代码
import json
json_file = r"G:\Desktop\python小项目\调用微信ocr进行识别文字\2.png.json"
save_file = "save.txt"

def save_text(json_file, save_file, mode=1):
    # 打开 JSON 文件
    with open(json_file, 'r', encoding='utf-8') as file:
        # 从文件中加载 JSON 数据
        data = json.load(file)
    # 换行保存
    if mode == 1:
        with open(save_file, 'w', encoding='utf-8') as f:
            # 提取每个对象的 text 字段
            for item in data['ocrResult']:
                print(item['text'])
                f.write(item['text'] + '\n')
    # 不换行保存
    if mode == 2:
        with open(save_file, 'w', encoding='utf-8') as f:
            # 提取每个对象的 text 字段
            for item in data['ocrResult']:
                print(item['text'])
                f.write(item['text'])


save_text(json_file, save_file, mode=2)

结论

json格式文件的读取的内容相对来说还是挺重要的,希望读者朋友们能看懂。

相关推荐
运维行者_8 小时前
企业无线网络监控的挑战与智能化演进趋势
大数据·运维·服务器·网络·数据库
国强_dev9 小时前
技术探讨:使用 stunnel 加密转发数据库连接时,如何获取客户端真实 IP?
数据库·网络协议·tcp/ip
@insist1239 小时前
系统规划与管理师-信息系统规划核心工作要点解析
数据库·软考·系统规划与管理师·软件水平考试·系统规划与管理工程师
超级数据查看器9 小时前
超级数据查看器 v10.0 发布
java·大数据·数据库·sqlite·安卓
数安3000天9 小时前
增量数据如何自动分类分级,避免目录“过期“?
大数据·数据库
南墙上的石头11 小时前
麒麟 V10 重装人大金仓 V8R6 踩坑实录(含 MySQL 兼容模式)
数据库·mysql
画中有画11 小时前
论向量数据库在项目中的应用
数据库
spider_xcxc12 小时前
Redis 数据库高质量实践指南(一)
运维·数据库·redis·oracle·云计算
l1t13 小时前
在linux和windows中解决duckdb 1.6dev版本输出执行计划报错问题
linux·运维·数据库·windows·duckdb
执子手 吹散苍茫茫烟波13 小时前
RC 隔离级别下 MySQL InnoDB 死锁典型案例
数据库·mysql