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.