← 返回 tesla 的题目列表Design a Configurable JSON Merge API
类型:online_judge
Problem: Design a Configurable JSON Merge API
Design and implement a JSON merge API that merges a patch into a base. The API must support at least two merge modes: overwrite and append.
For the coding version, the input is one JSON object:
{
"base": <JSON value>,
"patch": <JSON value>,
"mode": "overwrite" | "append"
}
Output the merged JSON value.
Merge Rules
If both base and patch are JSON objects (dictionaries), merge their keys recursively.
Keys present on only one side are kept directly.
In overwrite mode:
If two values at the same position cannot both be recursively merged as objects, the value from patch replaces the value from base.
Arrays are treated as non-recursively-mergeable values, so a patch array completely replaces a base array.
In append mode:
If both values at the same position are arrays, append all patch-array elements to the base array.
If both values are objects, merge recursively.
In all other cases, including scalar conflicts and type conflicts, patch replaces base.
Input is valid JSON, and mode is either overwrite or append.
Example
Input:
{"base":{"name":"car","tags":["ev"],"spec":{"range":300}},"patch":{"name":"new-car","tags":["luxury"],"spec":{"range":350,"color":"red"}},"mode":"append"}
Output:
{"name":"new-car","tags":["ev","luxury"],"spec":{"range":350,"color":"red"}}
Constraints
The total number of JSON object keys, array elements, and value nodes is at most 100,000.
Do not mutate the input base or patch values.
Example
Input
{"base":{"a":1,"b":{"x":10},"c":[1,2]},"patch":{"a":2,"b":{"y":20},"c":[3]},"mode":"overwrite"}
Output
{"a":2,"b":{"x":10,"y":20},"c":[3]}