Home > Blockchain >  How to extract particular data from JSON?
How to extract particular data from JSON?

Time:03-19

I am facing a small problem with a .json file. I would like to know how to extract particular data in Python3

This is my code :

with open("followers_log.json") as json_file:
    data = json.load(json_file)
    print(type(data))#dict
    print(data["data"][0]["username"])

My code works but only displays the first result. I would like to display all keys with the name "username" I've been searching on Google since yesterday but I couldn't find anything that could solve my problem.

Example of my json file

{
    "data": [
        {
            "id": "123",
            "name": "Example",
            "username": "example"
        },
        {
            "id": "456",
            "name": "example2",
            "username": "example2"
        },
        {
            "id": "789",
            "name": "example3",
            "username": "example3"
        },

An idea? Thank you

CodePudding user response:

try this

for each in data["data"]:
    print(each["username"])

CodePudding user response:

print(data["data"][0]["username"])

In the posted code the [0]-part refers to the first item in the list denoted as "data". (Indicated by the []-tags in your json-file.)

So, [0] refers to the following:

{
"id": "123",
"name": "Example",
"username": "example"
}

After which you refer to "username" returning "example".

So, in order to return each username, you need to loop over each item in the list provided by data["data"] as shown below:

for user in data["data"]:
    print(user["username"])
  • Related