如何解析嵌套的records JSON数组?附示例JSON结构
records Key Great question! Parsing nested JSON arrays with duplicate keys like records is super common—especially with APIs like Salesforce's, which your example clearly comes from. Let's break down how to handle this step by step, with practical examples in popular languages.
General Approach
The core idea is to traverse the JSON structure layer by layer:
- Parse the top-level JSON object to access the initial
recordsarray. - Iterate over each item in the top-level
records. - For each item, check if it contains a field (like
OrderItemshere) that holds another object with its ownrecordsarray. - If nested
recordsexist, repeat the process—use recursion if you need to handle unknown or deep levels of nesting.
Example Implementations
Python (Using Built-in json Module)
Python makes this straightforward with its native JSON tools:
import json # Your full JSON data (replace with your actual input string/file) json_str = """ { "totalSize":17, "done":true, "records":[ { "attributes":{ "type":"Order", "url":"/services/data/v51.0/sobjects/Order/8011m0000008c8WAAQ" }, "Id":"8011m0000008c8WAAQ", "DocumentType__c":null, "Orderno__c":null, "BiitoCustomerNo__c":null, "SelltoCustomerNo__c":null, "OrderDate__c":null, "PostingDate__c":null, "DocumentDate__c":null, "LocationCode__c":null, "Narration__c":null, "OrderCode__c":"Order - 000013", "OrderItems":null }, { "Id":"8011m0000008c0SAAQ", "DocumentType__c":null, "Orderno__c":null, "BiitoCustomerNo__c":null, "SelltoCustomerNo__c":null, "OrderDate__c":null, "PostingDate__c":null, "DocumentDate__c":null, "LocationCode__c":null, "Narration__c":null, "OrderCode__c":"Order - 000008", "OrderItems":{ "totalSize":2, "done":true, "records":[ { "attributes":{ "type":"OrderItem", "url":"/services/data/v51.0/sobjects/OrderItem/8021m000000DBirAAG" }, "Id":"8021m000000DBirAAG", "Document_Type__c":null, "Sell_to_Customer_No__c":null, "Item_Code__c":"OP-000004", "Variant_Code__c":null, "Location_Code__c":null, "Quantity":2, "Sales_Quantity__c":null, "Shipment_Date__c":null }, { "attributes":{ "type":"OrderItem", "url":"/services/data/v51.0/sobjects/OrderItem/8021m000000DBiqAAG" }, "Id":"8021m000000DBiqAAG", "Document_Type__c":null, "Sell_to_Customer_No__c":null, "Item_Code__c":"OP-000003", "Variant_Code__c":null, "Location_Code__c":null, "Quantity":2, "Sales_Quantity__c":null, "Shipment_Date__c":null } ] } } ] } """ # Parse the top-level JSON data = json.loads(json_str) # Iterate over top-level orders for order in data["records"]: print(f"Order: {order['OrderCode__c']} (ID: {order['Id']})") # Check for nested OrderItems records if order.get("OrderItems") and order["OrderItems"].get("records"): print(" Line Items:") for item in order["OrderItems"]["records"]: print(f" - {item['Item_Code__c']}: Quantity {item['Quantity']} (ID: {item['Id']})")
JavaScript (Using JSON.parse)
For frontend or Node.js environments, here's how to handle it:
// Your full JSON string const jsonStr = `{ "totalSize":17, "done":true, "records":[ { "attributes":{ "type":"Order", "url":"/services/data/v51.0/sobjects/Order/8011m0000008c8WAAQ" }, "Id":"8011m0000008c8WAAQ", "DocumentType__c":null, "Orderno__c":null, "BiitoCustomerNo__c":null, "SelltoCustomerNo__c":null, "OrderDate__c":null, "PostingDate__c":null, "DocumentDate__c":null, "LocationCode__c":null, "Narration__c":null, "OrderCode__c":"Order - 000013", "OrderItems":null }, { "Id":"8011m0000008c0SAAQ", "DocumentType__c":null, "Orderno__c":null, "BiitoCustomerNo__c":null, "SelltoCustomerNo__c":null, "OrderDate__c":null, "PostingDate__c":null, "DocumentDate__c":null, "LocationCode__c":null, "Narration__c":null, "OrderCode__c":"Order - 000008", "OrderItems":{ "totalSize":2, "done":true, "records":[ { "attributes":{ "type":"OrderItem", "url":"/services/data/v51.0/sobjects/OrderItem/8021m000000DBirAAG" }, "Id":"8021m000000DBirAAG", "Document_Type__c":null, "Sell_to_Customer_No__c":null, "Item_Code__c":"OP-000004", "Variant_Code__c":null, "Location_Code__c":null, "Quantity":2, "Sales_Quantity__c":null, "Shipment_Date__c":null }, { "attributes":{ "type":"OrderItem", "url":"/services/data/v51.0/sobjects/OrderItem/8021m000000DBiqAAG" }, "Id":"8021m000000DBiqAAG", "Document_Type__c":null, "Sell_to_Customer_No__c":null, "Item_Code__c":"OP-000003", "Variant_Code__c":null, "Location_Code__c":null, "Quantity":2, "Sales_Quantity__c":null, "Shipment_Date__c":null } ] } } ] }`; // Parse the JSON const data = JSON.parse(jsonStr); // Loop through orders data.records.forEach(order => { console.log(`Order: ${order.OrderCode__c} (ID: ${order.Id})`); // Check for nested line items if (order.OrderItems && order.OrderItems.records) { console.log(" Line Items:"); order.OrderItems.records.forEach(item => { console.log(` - ${item.Item_Code__c}: Quantity ${item.Quantity} (ID: ${item.Id})`); }); } });
Handling Deep/Unknown Nesting
If your JSON has multiple levels of nested records (not just one), use a recursive function to automatically traverse all levels. Here's a Python example:
def traverse_records(records, depth=0): indent = " " * depth for item in records: # Print a basic identifier (adjust based on your data's fields) if "Id" in item: print(f"{indent}ID: {item['Id']}") # Check all fields for nested records for key, value in item.items(): if isinstance(value, dict) and "records" in value: print(f"{indent}Nested records found under '{key}':") traverse_records(value["records"], depth + 1) # Call the recursive function on the top-level records traverse_records(data["records"])
This function will dig into every nested records array, no matter how deep it goes.
内容的提问来源于stack exchange,提问作者pandix

