How to take data from a JSON with Python

Asked

Viewed 1,967 times

4

I’m taking data from a JSON. Only I’m having a problem.

{  
    "atividade_principal":[  
        {  
            "text":"Atividades de televisão aberta",
            "code":"60.21-7-00"
        }
    ],
    "data_situacao":"03/11/2005",
    "nome":"GLOBO COMUNICACAO E PARTICIPACOES S/A"

I can get the data from nome and data_situacao. Only by taking the die from atividade_principal, everything that’s inside and I just want the text and code.

I’m using this code in Python to get the data. I can thus get the name.

 objeto = json.loads(objeto_texto)
 print = (objeto['nome'])

objeto is the JSON.

1 answer

4


To learn how to read and manipulate a JSON, it becomes easier when we understand its syntax:

  • what’s in the square brackets ([]) is an array: a list of multiple elements
  • what’s between the keys ({}) is an object: a set of key-value pairs

Your object has the key atividade_principal, whose value is an array (as it is bounded by []).

The first (and only) element of this array is an object (as it is bounded by {}). And this object, in turn, contains the keys text and code.

Then just take the first element of the array, and then take the keys text and code:

import json

objeto_texto = """
{
  "atividade_principal": [
    {
      "text": "Atividades de televisão aberta",
      "code": "60.21-7-00"
    }
  ],
  "data_situacao": "03/11/2005",
  "nome": "GLOBO COMUNICACAO E PARTICIPACOES S/A"
}
"""

objeto = json.loads(objeto_texto)
atividade = objeto['atividade_principal'][0]

print(atividade['text']) # Atividades de televisão aberta
print(atividade['code']) # 60.21-7-00

In the code above, objeto['atividade_principal'] returns the array corresponding to the key atividade_principal.

Then I use [0] to take the first element of the array (which in this case is the object containing the keys text and code). From there I can get the value of each one separately.


Also note that in the JSON you placed the lock key was missing (}) at the end, which I added in the code above.

Browser other questions tagged

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