python读取json并列_python解析多层json操作示例

Python解析多层JSON操作示例
本文给出Python解析多层JSON操作实例。先展示原始JSON文件内容,接着给出修改并保存的代码,通过遍历文件夹中文件,读取JSON数据并修改特定字段,最后覆盖写入。还推荐了几款实用的JSON在线工具,对Python程序设计有帮助。

本文实例讲述了python解析多层json操作。分享给大家供大家参考,具体如下:

原始文件内容:

{

"MaskPolygonItem": {

"0": {

"BoundingBox": "354.105 221.957 379.764 96.2241",

"label": "Number",

"labelNum": 0,

"polygon": "3,6"

}

},

"channels": 3,

"height": 1080,

"width": 1920

}

修改并保存代码

#coding=utf-8

import os

import json

#获取目标文件夹的路径

filedir = r'J:\NumberData\mrcnnHik\test'

#获取文件夹中的文件名称列表

filenames=os.listdir(filedir)

#遍历文件名

for filename in filenames:

filepath = filedir+'/'+filename

# print(filepath)

after = []

# 打开文件取出数据并修改,然后存入变量

with open(filepath, 'r') as f:

data = json.load(f)

mask=data["MaskPolygonItem"]

for zidian in mask:

print(type(zidian))

mask[zidian]["polygon"] = '354 221,355 310,729 318,733 236'

after = data

# 打开文件并覆盖写入修改后内容

with open(filepath, 'w') as f:

#结构化输出

data = json.dump(after, f,sort_keys=True, indent=4, separators=(',', ': '))

修改之后内容(仅修改了polygon)

{

"MaskPolygonItem": {

"0": {

"BoundingBox": "354.105 221.957 379.764 96.2241",

"label": "Number",

"labelNum": 0,

"polygon": "354 221,355 310,729 318,733 236"

}

},

"channels": 3,

"height": 1080,

"width": 1920

}

PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:http://tools.jb51.net/code/json

JSON在线格式化工具:http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

更多Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

本文标题: python解析多层json操作示例

本文地址: http://www.cppcns.com/jiaoben/python/296144.html

import json import os import sys def filter_xx_true(data): """递归筛选包含'xx':true的内容""" if isinstance(data, dict): # 检查当前字典是否包含目标键值对 if data.get("xx") is True: return data # 递归处理子元素 result = {} for key, value in data.items(): processed = filter_xx_true(value) if processed is not None: result[key] = processed return result if result else None elif isinstance(data, list): result = [] for item in data: processed = filter_xx_true(item) if processed is not None: result.append(processed) return result if result else None return None def process_file(input_path, output_path): """处理文件并导出结果""" try: with open(input_path, 'r', encoding='utf-8') as f_in, \ open(output_path, 'w', encoding='utf-8') as f_out: processed_count = 0 line_num = 0 for line in f_in: line_num += 1 line = line.strip() if not line: continue try: # 解析JSON并筛选 data = json.loads(line) result = filter_xx_true(data) if result is not None: # 格式化输出 json.dump(result, f_out, ensure_ascii=False, indent=2) f_out.write('\n\n') processed_count += 1 except json.JSONDecodeError: print(f"警告: 第 {line_num} 行JSON解析错误,已跳过") continue print(f"处理完成! 共处理 {line_num} 行,找到 {processed_count} 条匹配记录") print(f"结果已保存至: {os.path.abspath(output_path)}") except Exception as e: print(f"处理出错: {str(e)}") sys.exit(1) if __name__ == "__main__": if len(sys.argv) != 3: print("用法: python filter_xx_true.py 输入文件.txt 输出文件.txt") print("示例: python filter_xx_true.py data.txt results.txt") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] if not os.path.exists(input_file): print(f"错误: 输入文件不存在 - {input_file}") sys.exit(1) print(f"开始处理文件: {input_file}") process_file(input_file, output_file)这个代码处理json格式数据后,最小大括号外部的信息丢失了,我希望保留外部数据
最新发布
11-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值