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

如何在Flask中筛选包含ukuran键的JSON对象?

实现JSON对象筛选功能

原始JSON结构

{
       "id":"xyz",
       "word":"this is word",
       "formats":[ 
          {
             "formatId":"xz99",
             "pengeluaran":"pengeluaran_1"
          },
          {
             "formatId":"xy100",
             "pengeluaran":"pengeluaran_2"
          },
          {
             "ukuran":451563,
             "formatId":"xy101",
             "pengeluaran":"pengeluaran_1"
          }
       ]
}

需求

筛选出formats数组中包含ukuran键的对象,保留原结构的id、word字段,formats数组仅保留符合条件的对象,预期结果如下:

{
       "id":"xyz",
       "word":"this is word",
       "formats":[ 
          {
             "ukuran":451563,
             "formatId":"xy101",
             "pengeluaran":"pengeluaran_1"
          }
       ]
}

现有Python代码

def extractJson(appData):    
    appData = json.loads(output)
    
    //list comprehension to filter out only JSON object contain "ukuran"?

    print(appData)

解决方案

修改代码,用列表推导式完成筛选,同时修正原函数的参数逻辑问题:

import json

def extractJson(output):    
    # 解析JSON字符串为Python字典
    appData = json.loads(output)
    
    # 筛选formats中包含"ukuran"键的对象
    appData["formats"] = [item for item in appData["formats"] if "ukuran" in item]
    
    # 打印处理后的字典
    print(appData)
    # 若需要输出格式化的JSON字符串,可替换为以下语句
    # print(json.dumps(appData, indent=4))

代码说明

  1. 导入json模块,用于JSON的解析与序列化操作。
  2. 修正函数参数:原函数参数appData未被使用,改为直接传入JSON字符串output。
  3. 列表推导式[item for item in appData["formats"] if "ukuran" in item]遍历formats数组,仅保留包含ukuran键的对象,替换原formats数组内容。
  4. 若需要输出更易读的格式化JSON字符串,使用json.dumps(appData, indent=4)替代直接打印字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:33