How to Get the Location of a Key in a Nested JSON Object in Python
You can use the following Python code to get the location (index) of 'site2' within the 'sites' dictionary in your JSON object:
location = myObj['sites'].keys().index('site2')
This code snippet utilizes the index() method on a list of keys from the 'sites' dictionary. It returns the index value of 'site2', which is 1 in your example.
Once you have the index, you can use it to retrieve the value associated with 'site2' within the 'sites' dictionary:
value = myObj['sites'].values()[location]
This line uses the values() method to get a list of values from the 'sites' dictionary and then uses the location index to access the corresponding value, which is 'm.runoob.com' in your example.
原文地址: https://www.cveoy.top/t/topic/osr8 著作权归作者所有。请勿转载和采集!