DEV Community

Cover image for Get all keys and values from json object in Python
bluepaperbirds
bluepaperbirds

Posted on

Get all keys and values from json object in Python

In this Python tutorial we are going to see how we can get all the keys in this json object and also all the values of the keys.

okay so let me get started let me take one empty python file
here, so yeah so let me save this file first as example.py.

Load json

As it is a json i need to import this package called json. This lets you play around with json. Then it is available in this particular Python file.

import json
Enter fullscreen mode Exit fullscreen mode

Right so take that file path and try to open that with open as json file.

with open("C:\\pythonPrograms\\example.json") as jsonFile:
Enter fullscreen mode Exit fullscreen mode

That will do json decoding. Our json file looks like this:



    {"emp_details":[
             {"name": "a",
              "id": "123"
             },
             {"name":"b",
              "id":"345"
             }
    ]
    }


Enter fullscreen mode Exit fullscreen mode

You need to give the file name, so this is my file name. It should have double slashes not the single slash, so once we have this using the json library that we have imported you need to load the json object. Let's go.

Let's go

Get keys and values

Using load function json file, this let me keep it into a variable called data.



    data = json.load(jsonFile)


Enter fullscreen mode Exit fullscreen mode

Then you have a Python object. Now you can get the keys and values. The code below depends on what your json file looks like. In our json file there's a header named emp_details.



    jsonData = data["emp_details"]
    keys = x.keys()
    values = x.values()


Enter fullscreen mode Exit fullscreen mode

That gives us this code:



    import json

    with open("test.json") as jsonFile:
        data = json.load(jsonFile)
        jsonData = data["emp_details"]
        for x in jsonData:
            keys = x.keys()
            print(keys)
            values = x.values()
            print(values)


Enter fullscreen mode Exit fullscreen mode

It will output:

{'name': 'a', 'id': '123'}
dict_keys(['name', 'id'])
dict_values(['a', '123'])
{'name': 'b', 'id': '345'} 
dict_keys(['name', 'id'])
dict_values(['b', '345'])
Enter fullscreen mode Exit fullscreen mode

If you want, you can loop over the keys and values inside the loop, to do the formatting.

Here we use a for loop to iterate over the keys and values. If your json file is small like the one in this example, you don't necessarily have to use a loop.

That's all :-)

Top comments (0)