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

Groovy中未获取到指定键值对时如何设置默认值?

给JSON数组中缺失指定键的对象设置默认值

针对你需要为JSON数组中缺失Partner键的对象设置默认值0的需求,以下是几种常用编程语言的实现方案:

Python 实现

利用列表推导式结合字典的get()方法,快速为缺失键赋值:

import json

# 输入JSON数据
input_json = '''
[
{
    "Name": "1",
    "Partner": "11"
},
{
    "Name": "2"
},
{
    "Name": "3",
    "Partner": "33"
} 
]
'''

# 解析JSON为Python列表
data = json.loads(input_json)

# 处理每个对象,补充默认值
processed_data = [
    {**item, "Partner": item.get("Partner", 0)}
    for item in data
]

# 输出格式化后的JSON结果
print(json.dumps(processed_data, indent=2))

JavaScript 实现

使用数组map()方法遍历处理,通过空值合并运算符或条件判断补全默认值:

const inputData = [
  {
    "Name": "1",
    "Partner": "11"
  },
  {
    "Name": "2"
  },
  {
    "Name": "3",
    "Partner": "33"
  } 
];

// 处理数据,补全缺失的Partner值
const processedData = inputData.map(item => ({
  ...item,
  Partner: item.Partner ?? 0 // ES2020+ 空值合并运算符,仅当值为null/undefined时生效
  // 兼容旧版本可改用:item.hasOwnProperty('Partner') ? item.Partner : 0
}));

// 打印格式化结果
console.log(JSON.stringify(processedData, null, 2));

Java 实现(基于Jackson库)

借助Jackson解析JSON,遍历节点检查并补全缺失键:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.ArrayList;
import java.util.List;

public class JsonDefaultValueHandler {
    public static void main(String[] args) throws Exception {
        String inputJson = """
                [
                {
                    "Name": "1",
                    "Partner": "11"
                },
                {
                    "Name": "2"
                },
                {
                    "Name": "3",
                    "Partner": "33"
                } 
                ]""";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(inputJson);
        List<ObjectNode> processedList = new ArrayList<>();

        for (JsonNode node : rootNode) {
            ObjectNode objNode = (ObjectNode) node;
            // 检查是否存在Partner键,不存在则设置默认值0
            if (!objNode.has("Partner")) {
                objNode.put("Partner", 0);
            }
            processedList.add(objNode);
        }

        // 输出格式化后的JSON
        String outputJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(processedList);
        System.out.println(outputJson);
    }
}

所有方案的核心逻辑一致:遍历JSON数组中的每个对象,检查目标键是否存在,若缺失则为其赋值预设的默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:45:31