Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON nested Dictionary using Python

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
  }
}
like image 996
Software Fan Avatar asked Aug 10 '18 14:08

Software Fan


People also ask

How do you parse nested JSON data in Python?

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!

How do you get a value from a nested dictionary Python?

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 ).

How do I process nested JSON?

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.


1 Answers

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.

like image 121
Aeolus Avatar answered Sep 28 '22 03:09

Aeolus