自动化脚本优化:如何从数量不固定的JSON字典中高效提取DValue并组装请求参数
I'm writing an automation script and need to extract data from the following JSON output. The issue is that the number of elements in CValue isn't fixed—it can range from 1 to X sample values. My current approach is extremely inefficient, as I'm storing each value individually, which only works when there are exactly 2 DValue entries.
Sample JSON Output:
{ "Output": { "Name": "Sample", "Version": { "Errors": [], "VersionNumber": 2, "AValue": "Hello", "BValue": ["val:val:BVal"], "CValue": [ { "DValue": "aaaaa-bbbbb-cccc", "Name": "Sample_Name_1" }, { "DValue": "aaaaa-bbbbb-ddddd", "Name": "Sample_Name_2" } ] } }, "RequestId": "eeeee-fffff-gggg" }
Current Inefficient Code:
def get_sample_values(): test_get = command.sdk(xxxx) dset_1 = test_get['Output']['Version']['CValue'][0]['DValue'] dset_2 = test_get['Output']['Version']['CValue'][1]['DValue'] return dset_1, dset_2
Target Request Format:
I need to use these DValues as parameters in another function's request, which has this structure:
Source = { 'SourceReference': { 'DataReference': [ { 'EValue': 'string, string, string', 'FValue': DValue1 }, { 'EValue': 'string, string, string', 'FValue': DValue2 } ] } }
How can I implement this more efficiently to handle any number of DValue entries?
Got it, here's a scalable, efficient approach that handles any number of DValue entries in CValue:
Step 1: Extract All DValues Dynamically
Instead of hardcoding indexes like [0] or [1], use a list comprehension to iterate over every item in CValue and collect all DValues. This works no matter how many entries there are:
def get_sample_values(): test_get = command.sdk(xxxx) # Collect all DValues in a list d_values = [item['DValue'] for item in test_get['Output']['Version']['CValue']] return d_values
Step 2: Build the Request Structure Dynamically
Once you have the list of DValues, you can generate the DataReference list by looping through each DValue and creating the required dictionary entry for each. Again, this adapts automatically to the number of entries:
# Get all DValues d_values = get_sample_values() # Build the Source structure dynamically Source = { 'SourceReference': { 'DataReference': [ {'EValue': 'string, string, string', 'FValue': d_val} for d_val in d_values ] } }
Why This Works
- Scalability: Whether
CValuehas 1 entry or 100, the code will process all of them without any changes. - Readability: The list comprehensions make the code concise and easy to follow, compared to manual index assignments.
- Maintainability: If the structure of
CValueever changes (e.g., adding more fields), you only need to adjust one place instead of updating multiple hardcoded lines.
Bonus: Error Handling (Optional)
If you want to handle cases where CValue might be empty or missing, you can add a quick check to avoid KeyErrors or IndexErrors:
def get_sample_values(): test_get = command.sdk(xxxx) # Safely access nested keys and default to an empty list if any key is missing c_value = test_get.get('Output', {}).get('Version', {}).get('CValue', []) d_values = [item['DValue'] for item in c_value if 'DValue' in item] return d_values
This ensures your script doesn't crash if the JSON structure is incomplete or unexpected.
内容的提问来源于stack exchange,提问作者my_goodness

