Read Python Json file (beginner)

Asked

Viewed 1,094 times

-2

Good morning! I’m starting in python and I’m not able to read two specific fields in the generated json, with the following format:

    [
        {
            "nomeArq": "arquivoA",
            "dataAnt": "28042020",
            "dataAtu": "30042020",
            "qtdAnt": 1500,
            "qtdAtu": 2500,
            "percDif": 66.80
        },
        {
            "nomeArq": "arquivoB",
            "dataAnt": "28042020",
            "dataAtu": "30042020",
            "qtdAnt": 1000,
            "qtdAtu": 1700,
            "percDif": 70.00
        },
        {
            "nomeArq": "arquivoC",
            "dataAnt": "28042020",
            "dataAtu": "30042020",
            "qtdAnt": 2500,
            "qtdAtu": 2125,
            "percDif": -15.00
        }
    ]

When reading the file, it interprets it as a list, and I need to take the fields nameArq and percDif to make a graph in the pyplot. I can view the content in the field in a print, but I can’t make any moves or append the list I’ll use to generate the graph. I tried to convert to string but it also didn’t work:

with open(nomeArquivoJson, 'r') as jsonFileLeitura:
    dadosJson = json.load(jsonFileLeitura)
    print(dadosJson)
    print(dadosJson[0])
    print(dadosJson[0]['nomeArq'])

    for i in dadosJson:
        nomeOrg = str(dadosJson[i]['nomeOrg'])
        print(nomeOrg)

        listaNomeOrg.append(dadosJson[i]['nomeOrg'])
        listaPercVar.append(dadosJson[i]['percDif'])

print(listaNomeOrg)
print(listaPercVar)

The return, along with the error, is:

    [{'nomeArq': 'arquivoA', 'dataAnt': '28042020', 'dataAtu': '30042020', 'qtdAnt': 1500, 'qtdAtu': 2500, 'percDif': 66.8}, {'nomeArq': 'arquivoB', 'dataAnt': '28042020', 'dataAtu': '30042020', 'qtdAnt': 1000, 'qtdAtu': 1700, 'percDif': 70.0}, {'nomeArq': 'arquivoC', 'dataAnt': '28042020', 'dataAtu': '30042020', 'qtdAnt': 2500, 'qtdAtu': 2125, 'percDif': -15.0}]
    {'nomeArq': 'arquivoA', 'dataAnt': '28042020', 'dataAtu': '30042020', 'qtdAnt': 1500, 'qtdAtu': 2500, 'percDif': 66.8}
    arquivoA
    Traceback (most recent call last):
      File "/home/millena/Documentos/poc-monit/poc2GeraGraficov2.py", line 80, in <module>
        geraGrafico()
      File "/home/millena/Documentos/poc-monit/poc2GeraGraficov2.py", line 40, in geraGrafico
        nomeOrg = str(dadosJson[i]['nomeArq'])
    TypeError: list indices must be integers or slices, not dict

How do I read these two fields (nameArq and Percdif) to add them to a list to make the graph?

Thank you!

  • Two Errors: First that your JSON does not have the key [nomeOrg]. Second, when does dadosJson[i]['percDif'] the variable i is already an element of dadosJson obtained in for i in dadosJson: the error message is accusing that you are trying to use a complex object with key in the case of a list element itself, do i['percDif'].

  • Look at this example

1 answer

0


You can convert the list of dictionaries for a list dictionary filtering only the fields that interest you, see only:

import json

campos = ['nomeArq','percDif']

with open('teste.json') as f:
    entrada = json.load(f)

saida = {campo:[] for campo in campos}

for elemento in entrada:
    for campo in campos:
        saida[campo].append(elemento[campo])

print(saida)

Exit:

{'nomeArq': ['arquivoA', 'arquivoB', 'arquivoC'], 'percDif': [66.8, 70.0, -15.0]}

See working on Repl.it

Summarizing in a Dictionary comprehension combined with a comprehensilist on:

import json

campos = ['nomeArq','percDif']

with open('teste.json') as f:
    entrada = json.load(f)

saida = {c: [e[c] for e in entrada] for c in campos}

print(saida)

Exit:

{'nomeArq': ['arquivoA', 'arquivoB', 'arquivoC'], 'percDif': [66.8, 70.0, -15.0]}

See working on Repl.it

Line graph generation with the pyplot:

import matplotlib.pyplot as plt
import json

campos = ['qtdAnt', 'qtdAtu', 'percDif']

with open('teste.json') as f:
    entrada = json.load(f)

saida = {c: [e[c] for e in entrada] for c in campos}

for campo in campos:
    plt.plot(saida[campo], label=campo)

plt.legend()
plt.show()

Exit:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.