I have the following nested Dictionary in JSON. If I want to get "id", "self", "name", how should I parse it using a Python Program.
{
"items": [
{
"id": "12345",
"links": {
"self": "https://www.google.com"
},
"name": "beast",
"type": "Device"
}
],
"links": {
"self": "https://www.google.com"
},
"paging": {
"count": 1,
"limit": 1,
"offset": 0,
"pages": 1
}
}
Start by importing the json library. We use the function open to read the JSON file and then the method json. load() to parse the JSON string into a Python dictionary called superHeroSquad. That's it!
Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
A JSONArray can parse text from a String to produce a vector-like object. We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index). getString() method and it returns a string value at the specified position.
To understand how your json is set up, it's easier to break it down. Let's look at the first dictionary's keys, and remove the values.
json = {"items": [], "links": {}}
You have a dictionary with two keys and two values. All three of the variables you are looking for (id, self, name) are in the first key, "items". So let's dive deeper.
json["items"] = [{'links': {'self': 'https://www.google.com'}, 'name': 'beast', 'type': 'Device', 'id': '12345'}]
Now you have a list containing a dictionary with the values you are looking for, so let's enter the first and only value of the list containing the next dictionary.
json["items"][0] = {'links': {'self': 'https://www.google.com'}, 'id': '12345', 'type': 'Device', 'name': 'beast'}
Finally we have the dictionary with the values are looking for, so you can use this code to find name and id.
json["items"][0]["name"] = beast
json["items"][0]["id"] = 12345
The self variable is hidden one dictionary deeper so we have to delve into the links key.
json["items"][0]["links"]["self"] = http://google.com
Now you have all of your values, you just need to follow through all the lists and dictionaries to get the value you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With