0

Hi everyone! I need to get all the names in "streamers", but i really don't know how I can do this. Maybe you can help me.

Thanks!

JSON file:

    "streamers": [
        {},
        {
            "name": "One\n\n"
        },
        {
            "name": "Two\n\n"
        },
        {
            "name": "Three\n\n"
        }
    ]
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sam
  • 11
  • 2

3 Answers3

0

You can use the load method from json module. This function accepts a file handler, particularly a JSON file, then it converts it to a Python dictionary object which you can use right away in your code.

You can refer to the following snippet:

import json

f = open('path/to/file/file.json')      # Open the JSON file
dictionary = json.load(f)               # Parse the JSON file
f.close()                               # Close the JSON file

streamers = dictionary['streamers']
print(streamers)

Output


[
    {},
    {
        "name": "One\n\n"
    },
    {
        "name": "Two\n\n"
    },
    {
        "name": "Three\n\n"
    }
]
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33
0

okay so basically what you can do:

import json

names=[]
with open('data.txt') as json_file:
  dict=json.load(json_file)["streamers"]
  for tuple in dict:
    if "name" in tuple:
      names.append(tuple["name"]
print(names)
 

jojo_Berlin
  • 673
  • 1
  • 4
  • 19
0

Try:

import json

with open('path/to/file.json') as f:
    names = [x.get("name") for x in json.load(f)["streamers"] if x.get("name")]
    print(names)
Gabio
  • 9,126
  • 3
  • 12
  • 32