Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Como pegar um dado de um json usando python?

Olá! Tenho uma dúvida de como pegar dados de um json usando ipython. Exemplo:

{
   "/envi/cce/comcce/ide/MF":[
      "Element \\'{http://www.portal.com.br/cce}MF\\': [facet \\'pattern\\'] The value \\'\\' is not accepted by the pattern \\'[0-9]{7}\\'."
   ],
   "/envi/cce/comcce/ide/UF":[
      "Element \\'{http://www.portal.com.br/cce}UF\\': [facet \\'enumeration\\'] The value \\'n/a\\' is not an element of the set {\\'AC\\', \\'AL\\', \\'AM\\', \\'AP\\', \\'BA\\', \\'CE\\', \\'DF\\', \\'ES\\', \\'GO\\', \\'MA\\', \\'MG\\', \\'MS\\', \\'MT\\', \\'PA\\', \\'PB\\', \\'PE\\', \\'PI\\', \\'PR\\', \\'RJ\\', \\'RN\\', \\'RO\\', \\'RR\\', \\'RS\\', \\'SC\\', \\'SE\\', \\'SP\\', \\'TO\\', \\'EX\\'}."
   ],
   "/envi/cce/comcce/dest/enderDest/MU":[
      "Element \\'{http://www.portal.com.br/cce}MU\\': [facet \\'pattern\\'] The value \\'\\' is not accepted by the pattern \\'[0-9]{7}\\'."
   ],
   "/envi/cce/comcce/dest/enderDest/UF":[
      "Element \\'{http://www.portal.com.br/cce}UF\\': [facet \\'enumeration\\'] The value \\'n/a\\' is not an element of the set {\\'AC\\', \\'AL\\', \\'AM\\', \\'AP\\', \\'BA\\', \\'CE\\', \\'DF\\', \\'ES\\', \\'GO\\', \\'MA\\', \\'MG\\', \\'MS\\', \\'MT\\', \\'PA\\', \\'PB\\', \\'PE\\', \\'PI\\', \\'PR\\', \\'RJ\\', \\'RN\\', \\'RO\\', \\'RR\\', \\'RS\\', \\'SC\\', \\'SE\\', \\'SP\\', \\'TO\\', \\'EX\\'}."
   ]
}

Tentei dessas duas formas, mas não consegui:

In [44]: general_json.get('/envi/cce/comcce/ide/MF')                                                                                                                                              
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/opt/yara/const.py in <module>
----> 1 general_errors.get('/envi/cce/comcce/ide/MF')

AttributeError: 'list' object has no attribute 'get'

In [45]: general_json['/envi/cce/comcce/ide/MF']                                                                                                                                                  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/yara/const.py in <module>
----> 1 general_errors['/envi/cce/comcce/ide/MF]

TypeError: list indices must be integers or slices, not str

Agradeço a ajuda

1 resposta
solução!

Olá Yara, como vai?

Observe que o conteúdo da variável "general_json" é uma lista, sendo o primeiro item dessa lista, ou seja, "general_json[0]" o objeto JSON.

Tente da seguinte forma:

general_json[0].get('/enviCTe/CTe/infCte/ide/cMunFim')

Abs.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software