error using json_normalize on opened file

Question:

Why can I use the json_normalize function in a list written directly in the script but I can’t do it with the same data as an opened file?

Json sample:

resp = {"pagina": 1, "total_de_paginas": 3, "registros": 500, "total_de_registros": 1052, "produto_servico_cadastro":
[{"aliquota_cofins":0,
  "aliquota_ibpt":0,
  "aliquota_icms":0,
  "aliquota_pis":0,
  "altura":5,
  "bloqueado":"N",
  "bloquear_exclusao":"N",
  "cest":"",
  "cfop":"",
  "codInt_familia":"",
  "codigo":"10",
  "codigo_beneficio":"",
  "codigo_familia":3250197559,
  "codigo_produto":3250200206,
  "codigo_produto_integracao":"8531613751",
  "componentes_kit":[
     {
        "codigo_componente":3323761053,
        "codigo_produto_componente":3250202406,
        "local_estoque_componente":3244295942,
        "quantidade_componente":1,
        "valor_unitario_componente":13.1
     },
     {
        "codigo_componente":3253472053,
        "codigo_produto_componente":3250202411,
        "local_estoque_componente":3244295942,
        "quantidade_componente":1,
        "valor_unitario_componente":13.1
     }]}]}

script 1:

df_= resp['produto_servico_cadastro']
df_1 = pd.json_normalize(df_, record_path = ['componentes_kit'])

script 2:

In this example, I copied the contents of the resp variable and created a json file

f = open('/content/data.json')
dft = json.load(f)['produto_servico_cadastro']
dft_1 = pd.json_normalize(dft, record_path=['componentes_kit'])

results in

KeyError: 'componentes_kit'
Asked By: DTP – PEDRO

||

Answers:

This does actually work.

You will notice the key differences is how I have read the data (compared to the example code: script2).

In particular:

  • read the data from the file into data variable with f.read().
  • json.loads (copared to json.load)

If i copy the contents into a data.json file i can read it in exactly the same way like this:

import json
import pandas as pd

file = "C:\test\data.json"

with open(file) as f:
    data = f.read()

dft = json.loads(data)
dft = dft['produto_servico_cadastro']
dft_1 = pd.json_normalize(dft, record_path=['componentes_kit'])
df_1

And it produces the same dataframe:

   codigo_componente  codigo_produto_componente  local_estoque_componente  
0         3323761053                 3250202406                3244295942   
1         3253472053                 3250202411                3244295942   

   quantidade_componente  valor_unitario_componente  
0                      1                       13.1  
1                      1                       13.1  
Answered By: D.L

Unable to reproduce. No problem found.

>>> from pprint import pp
>>> pp(resp, sort_dicts=True)
{'pagina': 1,
 'produto_servico_cadastro': [{'aliquota_cofins': 0,
                               'aliquota_ibpt': 0,
                               'aliquota_icms': 0,
                               'aliquota_pis': 0,
                               'altura': 5,
                               'bloqueado': 'N',
                               'bloquear_exclusao': 'N',
                               'cest': '',
                               'cfop': '',
                               'codInt_familia': '',
                               'codigo': '10',
                               'codigo_beneficio': '',
                               'codigo_familia': 3250197559,
                               'codigo_produto': 3250200206,
                               'codigo_produto_integracao': '8531613751',
                               'componentes_kit': [{'codigo_componente': 3323761053,
                                                    'codigo_produto_componente': 3250202406,
                                                    'local_estoque_componente': 3244295942,
                                                    'quantidade_componente': 1,
                                                    'valor_unitario_componente': 13.1},
                                                   {'codigo_componente': 3253472053,
                                                    'codigo_produto_componente': 3250202411,
                                                    'local_estoque_componente': 3244295942,
                                                    'quantidade_componente': 1,
                                                    'valor_unitario_componente': 13.1}]}],
 'registros': 500,
 'total_de_paginas': 3,
 'total_de_registros': 1052}
>>> 
>>> fspec = '/tmp/data.json'
>>> 
>>> with open(fspec, 'w') as fout:
...     json.dump(resp, fout, indent=4, sort_keys=True)
... 
>>> 
>>> 
>>> f = open(fspec)
>>> dft = json.load(f)['produto_servico_cadastro']
>>> dft_1 = pd.json_normalize(dft, record_path=['componentes_kit'])
>>> 
>>> dft_1
   codigo_componente  codigo_produto_componente  local_estoque_componente  quantidade_componente  valor_unitario_componente
0         3323761053                 3250202406                3244295942                      1                       13.1
1         3253472053                 3250202411                3244295942                      1                       13.1
>>>
>>> pp(dft, sort_dicts=True)
[{'aliquota_cofins': 0,
  'aliquota_ibpt': 0,
  'aliquota_icms': 0,
  'aliquota_pis': 0,
  'altura': 5,
  'bloqueado': 'N',
  'bloquear_exclusao': 'N',
  'cest': '',
  'cfop': '',
  'codInt_familia': '',
  'codigo': '10',
  'codigo_beneficio': '',
  'codigo_familia': 3250197559,
  'codigo_produto': 3250200206,
  'codigo_produto_integracao': '8531613751',
  'componentes_kit': [{'codigo_componente': 3323761053,
                       'codigo_produto_componente': 3250202406,
                       'local_estoque_componente': 3244295942,
                       'quantidade_componente': 1,
                       'valor_unitario_componente': 13.1},
                      {'codigo_componente': 3253472053,
                       'codigo_produto_componente': 3250202411,
                       'local_estoque_componente': 3244295942,
                       'quantidade_componente': 1,
                       'valor_unitario_componente': 13.1}]}]
>>> 
Answered By: J_H
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.