jimkongho 2022-04-30 18:19 采纳率: 80%
浏览 37
已结题

json追加label的问题

import os
import json

path = r'C:\Users\jimkongHo\Desktop\1\2'
path1 = r'C:\Users\jimkongHo\Desktop\1\pic'
json_list = os.listdir(path)
json_listn = os.listdir(path1)

for jsonfn in json_listn:
if os.path.splitext(jsonfn)[1] == '.json':
print(jsonfn)
with open(os.path.join(path1,jsonfn),'r',encoding='utf-8')as fn:
contentn = json.load(fn)['shapes'][-1]
print(contentn)

for jsonf in json_list:
if os.path.splitext(jsonf)[1] == '.json':
print(jsonf)
with open(os.path.join(path,jsonf),'r',encoding='utf-8')as f:
content = json.load(f)['shapes'][-1]
content.update(contentn)

with open(os.path.join(path,jsonf),'a',encoding='utf-8')as fl:
json.dump(content,fl,indent=4)

上面的代码能成功把一个json的label数据追加到另一个json中,但我想要追加的位置在shapes里面,请问如何实现?追加的错误结果如下:
{
"version": "4.5.10",
"flags": {},
"shapes": [
{
"label": "1",
"points": [
[
4445.142857142857,
3789.7142857142853
],
[
5002.285714285714,
4432.5714285714275
]
],
"group_id": null,
"shape_type": "circle",
"flags": {}
}
],
"imagePath": "DSC00001.JPG",
"imageData": null,
"imageHeight": 6336,
"imageWidth": 9504,
"id": "02"
}{
"label": "object",
"points": [
[
4030.857142857142,
1175.4285714285706
],
[
4687.999999999999,
1718.2857142857138
]
],
"group_id": null,
"shape_type": "rectangle",
"flags": {}
}

我想要的效果如下:
{
"version": "4.5.10",
"flags": {},
"shapes": [
{
"label": "1",
"points": [
[
4445.142857142857,
3789.7142857142853
],
[
5002.285714285714,
4432.5714285714275
]
],
"group_id": null,
"shape_type": "circle",
"flags": {}
},
{
"label": "object",
"points": [
[
4030.857142857142,
1175.4285714285706
],
[
4687.999999999999,
1718.2857142857138
]
],
"group_id": null,
"shape_type": "rectangle",
"flags": {}
}
],
"imagePath": "DSC00001.JPG",
"imageData": null,
"imageHeight": 6336,
"imageWidth": 9504,
"id": "02"
}

  • 写回答

1条回答 默认 最新

  • Bug 终结者 Java领域优质创作者 2022-04-30 21:51
    关注

    可以使用 map 集合进行追加

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月9日
  • 已采纳回答 5月2日
  • 创建了问题 4月30日

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题