Estrazione dei dati dal file JSON in Python [duplicato]

Nov 08 2020

Ciao a tutti! Devo trovare tutti i nomi in "streamer", ma davvero non so come posso farlo. Forse puoi aiutarmi.

Grazie!

File JSON:

    "streamers": [
        {},
        {
            "name": "One\n\n"
        },
        {
            "name": "Two\n\n"
        },
        {
            "name": "Three\n\n"
        }
    ]
}

Risposte

jojo_Berlin Nov 08 2020 at 01:51

ok quindi in pratica cosa puoi fare:

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)
 

MelvinAbraham Nov 08 2020 at 01:49

Puoi usare il loadmetodo da jsonmodule. Questa funzione accetta un gestore di file, in particolare un file JSON, quindi lo converte in un oggetto dizionario Python che puoi usare subito nel tuo codice.

Puoi fare riferimento al seguente frammento:

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)

Produzione


[
    {},
    {
        "name": "One\n\n"
    },
    {
        "name": "Two\n\n"
    },
    {
        "name": "Three\n\n"
    }
]
Gabip Nov 08 2020 at 02:00

Provare:

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)