python解析多层json操作示例

yipeiwu_com5年前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性能优化的20条建议

优化算法时间复杂度 算法的时间复杂度对程序的执行效率影响最大,在Python中可以通过选择合适的数据结构来优化时间复杂度,如list和set查找某一个元素的时间复杂度分别是O(n)和O(...

python2 与 python3 实现共存的方法

python2 与 python3 实现共存的方法

1.现在我本机系统已内置python2.6 2.下载进行源码安装 复制链接下载到/root/mypackage,解压 接着 mkdir /usr/local/python3 然后在解...

python任务调度实例分析

本文实例讲述了python任务调度实现方法。分享给大家供大家参考。具体如下: 方法1: import sched, time import os s = sched.schedule...

python启动应用程序和终止应用程序的方法

1. 目的 每天上班,工作需要,电脑上需要每天开机启动一些软件,下班时候,需要关掉一些软件。一个一个打开和关闭貌似是很繁琐的,于是乎,这个脚本产生了。 2. 环境 系统环境: - win...

Python利用pandas计算多个CSV文件数据值的实例

功能:扫描当前目录下所有CSV文件并对其中文件进行统计,输出统计值到CSV文件 pip install pandas import pandas as pd import glob...