Python-aligned JSON output

Asked

Viewed 41 times

2

I have the following Json to be treated in python:

{
   "lojas": {
      "todas":[
         {
            "CodigoLoja": "001",
            "produtos":[
               {
                  "CodigoProduto": "001AAAAAAA",
                  "dataFabricacao": "11/11/2019",
                  "preco": "300,00"
               },
               {
                  "CodigoProduto": "001BBBBBBB",
                  "dataFabricacao": "2020-11-11",
                  "preco": "400,00"
               }
            ]
         },
         {
            "codigoLoja": "002",
            "produtos":[
               {
                  "CodigoProduto": "002AAAAAAA",
                  "dataFabricacao": "11/11/2018",
                  "preco": "500,00"
               },
               {
                  "CodigoProduto": "002BBBBBBB",
                  "dataFabricacao": "2017-11-11",
                  "preco": "600,00"
               }
            ]
         }
      ]
   }
}

The formatted output I seek is:

codigoLoja      codigoProduto dataFabricacao      preco
001             001AAAAAAA    2019-11-11          300,00
001             001BBBBBBB    2020-11-11          400,00
002             002AAAAAAA    2018-11-11          500,00
002             002BBBBBBB    2017-11-11          600,00
       

I’m doing it this way:

for each in data['lojas']['todas']:
    for produtos in each['produtos']:
        print(each['codigoLoja']+produtos['codigoProduto']+produtos['dataFabricacao']+produtos['preco']) 

This even works, but I wonder if there is a better way to implement, without having to define the name of the fields, because if you include a new field in products (for example, "product description"), do not have to keep changing the code.

  • Try a pandas implementation. The solution will be simpler and possibly you will be able to automate for any key names entry.

1 answer

1


By your example, I understand that the JSON structure has been converted to a dictionary structure.

Loop the product inside.

for each in data['lojas']['todas']:
    for produto in each['produtos']:
        linha = each['codigoLoja']
        for chave, valor in produto.items():
            linha += valor
        print(linha)   

Realize that linha += valor will put all "pasted" values as the example below:

001001AAAAAAA2019-11-11300,00

To get this right, I suggest you look at the methods .ljust(), .rjust()

The loop would be as below:

linha = each['codigoLoja'].ljust(20)
for chave, valor in produto.items():
    linha += valor.rjust(20)

However this solution would keep a fixed value of 20 positions for each field. Leaving as below, for example:

001                 001AAAAAAA          2019-11-11          300,00

I hope it helps.

Browser other questions tagged

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