You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从现有JSON中提取指定键值对构造新的JSON对象

解决方案

你可以直接使用如下JMESPath表达式完成字段提取和过滤,完全匹配你的需求:

{
  duration: duration,
  frame_id: frame_id,
  detect1: detect1.[
    {
      type: {
        s_type1: [type.s_type1[0].{confidence: confidence, name: name}],
        s_type2: [type.s_type2[0].{confidence: confidence, name: name}],
        Box: type.Box
      },
      confidences: confidences
    }
  ]
}

表达式规则说明

  • 顶层直接保留duration、frame_id字段的原始值
  • 遍历detect1数组,对数组内每个对象做如下处理:
    • 取type下s_type1数组的第一个元素,仅保留confidence和name字段后重新封装为数组
    • 按相同规则处理type下的s_type2数组
    • 直接保留type下的Box字段完整内容
    • 直接保留detect1对象下的confidences字段完整内容

Python 运行示例

import jmespath
import json

# 原始JSON数据
raw_data = json.loads('''
{
    "duration": 1942,
    "frame_id": 0,
    "detect1": [
        {
            "type": {
                "s_type1": [
                    {
                        "confidence": 98.70016,
                        "klass": -1,
                        "name": "c*****"
                    },
                    {
                        "confidence": 1.042385,
                        "klass": -1,
                        "name": "c*****"
                    },
                    {
                        "confidence": 0.1587732,
                        "klass": -1,
                        "name": "s*****"
                    }
                ],
                "s_type2": [
                    {
                        "confidence": 92.82484,
                        "klass": -1,
                        "name": "b*****"
                    },
                    {
                        "confidence": 7.098834,
                        "klass": -1,
                        "name": "b*****"
                    },
                    {
                        "confidence": 0.02423214,
                        "klass": -1,
                        "name": "p*****"
                    }
                ],
                "Box": [
                    80.80994,
                    170.0965,
                    1091.778
                ]
            },
            "confidences": [
                90.08681,
                99.91595,
                90.12489
            ]
        }
    ]
}
''')

# 执行查询
result = jmespath.search('''
{
  duration: duration,
  frame_id: frame_id,
  detect1: detect1.[
    {
      type: {
        s_type1: [type.s_type1[0].{confidence: confidence, name: name}],
        s_type2: [type.s_type2[0].{confidence: confidence, name: name}],
        Box: type.Box
      },
      confidences: confidences
    }
  ]
}
''', raw_data)

# 打印结果
print(json.dumps(result, indent=4))

运行上述代码即可直接输出你需要的目标JSON结构。


内容的提问来源于stack exchange,提问作者Ib D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:36:04