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"
        }
    ]
}
1
  • Does the json module documentation in the Python docs not help? Commented Nov 7, 2020 at 18:44

3 Answers 3

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)
 

Sign up to request clarification or add additional context in comments.

Comments

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"
    }
]

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.