Java中递归排序JSON数组与对象属性的实现方法
Recursively Sort JSON Arrays by Object "Name" Property (Supports Nested Arrays)
Hey there, let's walk through solving this problem exactly as you described: parsing a JSON string, recursively checking every object property and array element, sorting any array where all items are objects with a Name property (even if nested 3+ levels deep), then serializing it back to JSON.
I'll share solutions in two popular languages—JavaScript and Python—since they're commonly used for JSON processing.
JavaScript Implementation
This recursive function will handle any depth of nested arrays, including your 3-level use case:
function sortArraysByName(obj) { // First handle array types if (Array.isArray(obj)) { // Verify every element is an object with a "Name" property const allHaveName = obj.every(item => typeof item === 'object' && item !== null && 'Name' in item ); if (allHaveName) { // Sort by "Name" (use toLowerCase() inside localeCompare for case-insensitive sort) return obj.sort((a, b) => a.Name.localeCompare(b.Name)); } // If not all elements have "Name", recursively process each item return obj.map(item => sortArraysByName(item)); } // Next handle object types if (typeof obj === 'object' && obj !== null) { // Recursively process each property value return Object.fromEntries( Object.entries(obj).map(([key, value]) => [key, sortArraysByName(value)]) ); } // Return primitive values (strings, numbers, booleans, null) as-is return obj; } // Example usage const inputJson = `{ "Level1": [ { "Name": "Zebra", "Level2": [ { "Name": "Banana", "Level3": [ { "Name": "Xray" }, { "Name": "Apple" } ]} ]}, { "Name": "Apple", "Level2": [ { "Name": "Orange" } ]} ] }`; // Parse, process, serialize back to JSON const parsedData = JSON.parse(inputJson); const sortedData = sortArraysByName(parsedData); const outputJson = JSON.stringify(sortedData, null, 2); console.log(outputJson);
Key Notes for JavaScript:
- Case Insensitivity: To make the sort case-insensitive, modify the sort comparator to
a.Name.toLowerCase().localeCompare(b.Name.toLowerCase()). - Edge Case Handling: If an array has a mix of objects with/without
Nameor non-object elements, the function skips sorting that array and continues processing nested items.
Python Implementation
Python's approach follows the same recursive logic, perfect for nested JSON structures:
import json def sort_arrays_by_name(obj): if isinstance(obj, list): # Check if all items are dictionaries containing the "Name" key all_have_name = all( isinstance(item, dict) and "Name" in item for item in obj ) if all_have_name: # Sort by "Name" (add .lower() to the key for case-insensitive sorting) return sorted(obj, key=lambda x: x["Name"]) # Recursively process each element in the list return [sort_arrays_by_name(item) for item in obj] elif isinstance(obj, dict): # Recursively process each value in the dictionary return {key: sort_arrays_by_name(value) for key, value in obj.items()} # Return non-collection values (strings, numbers, booleans, None) unchanged return obj # Example usage input_json = '''{ "Level1": [ { "Name": "Zebra", "Level2": [ { "Name": "Banana", "Level3": [ { "Name": "Xray" }, { "Name": "Apple" } ]} ]}, { "Name": "Apple", "Level2": [ { "Name": "Orange" } ]} ] }''' # Parse, process, serialize back to JSON parsed_data = json.loads(input_json) sorted_data = sort_arrays_by_name(parsed_data) output_json = json.dumps(sorted_data, indent=2) print(output_json)
Key Notes for Python:
- Case Insensitivity: Adjust the sort key to
lambda x: x["Name"].lower()for case-insensitive sorting. - Flexible Depth: This function works for any number of nested array levels, not just three—so it'll handle deeper structures if your JSON ever expands.
内容的提问来源于stack exchange,提问作者John Arrowwood
相关产品推荐
相关产品推荐

