Access data from a JSON structure

Asked

Viewed 2,356 times

1

I’m having some problems trying to access some data in a JSON structure.

The JSON code is this:

[
    {
        "teste":[
            {
                "dados":"teste",
                "uno":[
                    {
                        "um":"Teste",
                        "cores":[
                            {
                                "preto":"Preto",
                                "branco":"Branco"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

How do I give the print of only one of these data? For example, I would like to access only the content contained in "preto" by the program written in Python. Or access only what is contained within "dados".

3 answers

2


The other answers already gave the code that does what you need. But just to complement, I think it’s important you understand the format of a JSON, so you can work better with any data in the future.

The syntax of a JSON can be consulted here. In a very concise way, we can divide the data types into:

  • "basic" values: numbers, strings, booleans
  • arrays: an ordered list of values
  • objects: a set of pairs "key: value" (without defined order)

The keys of an object are strings, and the value can be any of the above (a number, a string, an array, or another object). The values of an array can also be any (number, string, objects, other array).

An array is bounded by square brackets ([ and ]): everything inside the brackets are elements of the array, and they are separated by a comma. Then [1, "abc", 2] is an array with 3 elements (number 1, string "abc" and number 2 in this order).

An object is bounded by { and }, and the pairs "key: value" are separated by a comma. Then { "nome" : "Fulano", "idade": 30 } is an object that holds the key "nome", whose value is the string "Fulano", and the key "idade", the value of which is number 30.

The detail is that - as mentioned above - the values within an array or object can be other arrays and objects. Examples:

[10, { "nome": "Fulano", "idade": 30} ]

The above example is an array with 2 elements: number 10 and an object with keys "nome" and "idade".


{ "nome": "Fulano", "idade": 30, "filmes_preferidos": [ "Star Wars", "Clube da Luta" ] }

The example above is an object with 3 keys: "nome" (whose value is the string "Fulano"), "idade" (the value of which is number 30) and "filmes_preferidos" (whose value is an array containing two strings: "Star Wars" and "Clube da Luta").

There is no theoretical limit to the nesting of these structures (perhaps only practical limits dependent on implementation). We may have an array containing objects, which in turn contains arrays, which contains other objects, which may contain more objects and so on.


In your case, we have:

[ <-- início do array
    { <-- primeiro elemento do array é um objeto
        "teste":[   <- chave "teste", cujo valor é um array
            {       <- dentro deste array temos outro objeto
                "dados":"teste",  <- chave "dados", valor "teste"
                "uno":[           <- chave "uno", valor é um array
                    {                 <- dentro deste array, temos outro objeto
                        "um":"Teste",   <- chave "um", valor "Teste"
                        "cores":[       <- chave "cores", valor é um array
                            {             <- dentro deste array, temos outro objeto
                                "preto":"Preto",   <- chave "preto", valor "Preto"
                                "branco":"Branco"  <- chave "branco", valor "Branco"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

That is, it is an array that has an object, whose only key has another array, which has another object, which has a key that contains another array, which in turn has another object, with another array containing another object.

Without getting into the merits of this structure being very complex (and without more context you can’t tell if it is suitable or not), several languages have Apis to manipulate data in JSON format and turn them into structures of the language itself.

In the case of Python, module json does the conversion using this table:

JSON Python
Object Dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Using the same solution as the other answers, you can do the Parsing of a string containing a JSON using the method loads:

import json

JSON = """[
{
    "teste":[
        {
            "dados":"teste",
            "uno":[
                {
                    "um":"Teste",
                    "cores":[
                        {
                            "preto":"Preto",
                            "branco":"Branco"
                        }
                    ]
                }
            ]
        }
    ]
    }
]"""

dados = json.loads(JSON)

Following the table above, dados will be mapped to a list (since the original JSON is an array). Since this array has only one element (which is an object), then dados[0] (the first element of the list) will be a dict.

This object, in turn, has the key "teste", whose value can be accessed with dados[0]['teste'] - and this, in turn, is another array, which has a single element: the object that holds the keys "dados" and "uno" (and to get it, just take the first element from the list: dados[0]['teste'][0]).

Then we can take each of the keys with dados[0]['teste'][0]['dados'] and dados[0]['teste'][0]['uno'] (the first returns the string "teste" and the second returns a list, whose only element is the object that holds the keys "um" and "cores"). And so on and so forth.

By following this reasoning it is possible to arrive at the values you need:

print(dados[0]['teste'][0]['dados']) # teste
print(dados[0]['teste'][0]['uno'][0]['cores'][0]['preto']) # Preto

1

You can use the function loads() module json which is able to read a string containing data in JSON format and convert it to a primitive data structure composed basically of listas and dicionários, look at you:

import json

JSON = """[
{
    "teste":[
        {
            "dados":"teste",
            "uno":[
                {
                    "um":"Teste",
                    "cores":[
                        {
                            "preto":"Preto",
                            "branco":"Branco"
                        }
                    ]
                }
            ]
        }
    ]
    }
]"""

dados = json.loads(JSON)
print(dados)

Exit:

[{'teste': [{'uno': [{'cores': [{'branco': 'Branco', 'preto': 'Preto'}], 'um': 'Teste'}], 'dados': 'teste'}]}]

Accessing the content of black:

print( dados[0]['teste'][0]['uno'][0]['cores'][0]['preto'] )

Accessing the content of dice:

print( dados[0]['teste'][0]['dados'] )

0

Thus:

import json 

json_str = """[
{
    "teste":[
        {
            "dados":"teste",
            "uno":[
                {
                    "um":"Teste",
                    "cores":[
                        {
                            "preto":"Preto",
                            "branco":"Branco"
                        }
                    ]
                }
            ]
        }
    ]
}
]"""

json_list = json.loads(json_str)

print(json_list[0]['teste'][0]['dados'])

Browser other questions tagged

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