Java中将指定JSON Object转换为JSON Array的实现方案求助
Got it, let's walk through how to achieve this transformation clearly. This is a typical use case where you need to "spread" common properties across every item in a nested array. Here's the step-by-step approach:
Core Implementation Steps
- Extract Shared Fields First: Pull out the key-value pairs that need to be present in every result object (in your case,
key1,key2,key3) and store them in a separate reusable object. This avoids repeating code and makes updates easier later. - Iterate Over the Nested Array: Target the array in your original object (
key4here) and loop through each of its items. - Merge Objects: For each item in the array, combine the shared fields object with the current item. This creates a new object that includes both the common properties and the item-specific ones.
- Collect Results: Gather all these merged objects into a new array, which will be your final desired output.
Code Examples
JavaScript
This uses the spread operator (...) for clean object merging:
// Your original JSON object const originalData = { "key1": "value1", "key2": "value2", "key3": "value3", "key4": [ { "key5":"value5", "key6":"value6" }, { "key7":"value7", "key8":"value8" }, { "key9":"value9", "key0":"value0" } ] }; // Extract the common fields const sharedProps = { key1: originalData.key1, key2: originalData.key2, key3: originalData.key3 }; // Map over the nested array and merge each item with shared props const transformedArray = originalData.key4.map(item => ({ ...sharedProps, ...item })); console.log(transformedArray);
Python
Using dictionary unpacking to merge objects:
original_data = { "key1": "value1", "key2": "value2", "key3": "value3", "key4": [ { "key5":"value5", "key6":"value6" }, { "key7":"value7", "key8":"value8" }, { "key9":"value9", "key0":"value0" } ] } # Extract common fields using a dictionary comprehension shared_props = {k: original_data[k] for k in ["key1", "key2", "key3"]} # List comprehension to merge and collect results transformed_array = [{**shared_props, **item} for item in original_data["key4"]] print(transformed_array)
Quick Note on Edge Cases
If any item in the key4 array has a key that overlaps with your shared fields (e.g., an item has its own key1), the item's value will override the shared one during merging. If you need to handle this scenario (like preventing overrides), you can add a check before merging to prioritize one set of values over the other.
内容的提问来源于stack exchange,提问作者user3214665
相关产品推荐
相关产品推荐

