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

如何移除REST API返回JSON中空字符串对应的键?

过滤JSON对象中空字符串属性

我从REST API获取到如下JSON数据:

[
  {
    "id": 58939956,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "",
    "goal_type": ""
  },
  {
    "id": 58939957,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "2023-11-01",
    "goal_type": "cpc"
  }
]

API未提供属性时会返回空字符串作为对应键的值,需要过滤掉每个对象中值为空字符串的键,期望输出:

[
  {
    "id": 58939956,
    "campaign_id": 1012995497,
    "status": 0
  },
  {
    "id": 58939957,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "2023-11-01",
    "goal_type": "cpc"
  }
]

实现方案

JavaScript 实现

遍历数组中的每个对象,过滤掉值为空字符串的键:

const originalData = [
  {
    "id": 58939956,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "",
    "goal_type": ""
  },
  {
    "id": 58939957,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "2023-11-01",
    "goal_type": "cpc"
  }
];

const filteredData = originalData.map(item => {
  return Object.fromEntries(
    Object.entries(item).filter(([key, value]) => value !== "")
  );
});

console.log(JSON.stringify(filteredData, null, 2));

Python 实现

遍历每个字典,剔除值为空字符串的键:

import json

original_data = [
  {
    "id": 58939956,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "",
    "goal_type": ""
  },
  {
    "id": 58939957,
    "campaign_id": 1012995497,
    "status": 0,
    "start_time": "2023-11-01",
    "goal_type": "cpc"
  }
]

filtered_data = []
for item in original_data:
    filtered_item = {k: v for k, v in item.items() if v != ""}
    filtered_data.append(filtered_item)

print(json.dumps(filtered_data, indent=2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:57:37