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

Java中JSON树遍历:如何根据节点Key处理嵌套结构

遍历嵌套JSON树并根据Key执行分支逻辑

Got it, let's work through this together — you're trying to traverse a nested JSON-style tree where each node's key tells you how to process its children, and your pseudocode is almost there but has a few easy fixes. Let's break this down step by step.

核心思路:递归遍历 + 分支逻辑

Since JSON trees are inherently recursive (nodes can have children that are themselves nodes), recursion is the perfect tool here. The basic flow is:

  • For any given node, check its key to determine what operation to run
  • For operations that need child values (like ADD/MULT), recursively traverse each child to get its computed value
  • Combine those child values according to the node's key
  • Handle leaf nodes (nodes without children, like raw numbers) by returning their value directly

修正你的伪代码并完善逻辑

First, let's fix the issues in your original pseudocode:

  • You duplicated the ADD check (probably a typo)
  • MULT starts with res = 0 — that's a bug! Multiplying by 0 will always give 0, so you need to start with res = 1
  • You used children instead of child in the loop (a variable name mix-up)

Here's the cleaned-up pseudocode:

int traverse(node) {
    // Handle leaf nodes (e.g., numeric values with no children)
    if (node has no children) {
        return node.value;
    }

    int res;
    switch(node.key) {
        case "ADD":
            res = 0;
            for each child in node.children:
                res += traverse(child);
            break;
        case "MULT":
            res = 1;
            for each child in node.children:
                res *= traverse(child);
            break;
        // Add more cases for other keys (SUB, DIV, etc.)
        default:
            throw error("Unknown operation key: " + node.key);
    }
    return res;
}

实际代码示例(Python)

Let's translate this to real code using Python, since it's great for handling JSON structures (which parse into dicts/lists):

Suppose your JSON tree looks like this:

{
    "key": "MULT",
    "children": [
        {"key": "ADD", "children": [{"value": 2}, {"value": 3}]},
        {"value": 4}
    ]
}

Here's the traversal function:

def traverse(node):
    # Check if it's a leaf node (has a value instead of children)
    if "value" in node:
        return node["value"]
    
    # Get the operation key and children
    op_key = node["key"]
    children = node["children"]
    
    if op_key == "ADD":
        result = 0
        for child in children:
            result += traverse(child)
    elif op_key == "MULT":
        result = 1
        for child in children:
            result *= traverse(child)
    else:
        raise ValueError(f"Unsupported operation: {op_key}")
    
    return result

# Test with the sample JSON tree
sample_tree = {
    "key": "MULT",
    "children": [
        {"key": "ADD", "children": [{"value": 2}, {"value": 3}]},
        {"value": 4}
    ]
}

print(traverse(sample_tree))  # Output: 20 (since (2+3)*4 = 20)

Key Notes for Edge Cases

  • Leaf Nodes: Always make sure your function checks for leaf nodes first (nodes with a value instead of children) — otherwise, you'll get errors trying to access key or children on numeric nodes.
  • Empty Children: What if an ADD/MULT node has no children? You might want to handle that explicitly (e.g., return 0 for empty ADD, 1 for empty MULT) to avoid unexpected behavior.
  • Other Operations: Adding support for SUB (subtraction) or DIV (division) would require adjusting the logic — for example, SUB might take the first child's value and subtract the rest, while DIV would need to avoid division by zero.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:25:16