Find the Key of Nested JSON Object in Python
You can iterate through the first layer of the JSON object and check if the value of the second key in each element matches the known value in layer 2. If it does, you can return the name of the second key in that element.
Here's some sample code in Python:
import json
# Example nested JSON
data = {
'layer1_key1': {
'layer2_key1': {
'nested_key1': 'nested_value1'
}
},
'layer1_key2': {
'layer2_key2': {
'nested_key2': 'nested_value2'
}
}
}
known_value = 'nested_value2'
# Iterate through layer 1 and check if layer 2 value matches
for key in data.keys():
layer2 = data[key].get('layer2_key1', None) # Change 'layer2_key1' to the actual name of the second key in layer 1
if layer2 and layer2.get('nested_key2', None) == known_value: # Change 'nested_key2' to the actual name of the key in layer 2
print(key) # This is the name of the second key in layer 1 that has the nested JSON object
In this example, the code will output 'layer1_key2' since that is the name of the second key in layer 1 that has the nested JSON object with a value of 'nested_value2' in layer 2.
原文地址: https://www.cveoy.top/t/topic/ossQ 著作权归作者所有。请勿转载和采集!