-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 doesdadosJson[i]['percDif']
the variablei
is already an element ofdadosJson
obtained infor 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, doi['percDif']
.– Augusto Vasques
Look at this example
– Augusto Vasques