Browse and count records from a JSON

Asked

Viewed 1,491 times

2

I have a Python code that I can display on the screen all JSON records, only I need to bring only the field 'Nome' and the count of each.

First he brings with [] (list format) and I need the information clean, but I don’t know how to get it.

Ex.:

    {  
   'contract_id':300166,
   'plan_id':15,
   'total_value':39.9,
   'installment_value':0.0,
   'agent_code':'nenhum',
   'customer_name':'Rafael Moura dos Santos',
   'customer_cpf':'54745361602',
   'status':'cancelado',
   'payment_link':None,
   'installments':12,
   'payment_method':None,
   'validity_start_date':'2017-11-07 00:00:00',
   'validity_end_date':'2018-11-07 00:00:00',
   'addresses':[  
      {  
         'street':'rua da ovelha',
         'number':'999',
         'additional_details':'bloco do completo',
         'zipcode':'07121010',
         'district':'water',
         'city':'agua',
         'state':'SP',
         'country':'BR'
      }
   ],
   'phones':[  
      {  
         'category':'mobile',
         'extension':'',
         'number':'5511981013752'
      }
   ],
   'customer':{  
      'name':'Rafael Moura dos Santos',
      'cpf':'54745361602',
      'birth':'1988-06-28',
      'gender':'',
      'marital_status':''
   },
   'links':[  

   ],
   'policies':[  
      {  
         'policy_id':210,
         'policy_number':'PA-000090',
         'certificate_link':'',
         'value':39.9,
         'status':'ativo',
         'product_id':1,
         'metadata':{  

         },
         'covered_goods':[  
            {  
               'Nome':'Rex',
               'Cão ou gato':'Cão',
               'Cor do pelo':'Marrom',
               'Data de nascimento':'29/03/2010',
               'Tamanho':'M',
               'Macho ou Fêmea':'Macho',
               'Raça':'Arc',
               'Doença ou lesão preexistente':'Não',
               'Descreva preexistência':'',
               'Vacinação em dia':'Sim'
            },
            {  
               'Nome':'Rex',
               'Cão ou gato':'Cão',
               'Cor do pelo':'Marrom',
               'Data de nascimento':'29/03/2010',
               'Tamanho':'M',
               'Macho ou Fêmea':'Macho',
               'Raça':'Arc',
               'Doença ou lesão preexistente':'Não',
               'Descreva preexistência':'',
               'Vacinação em dia':'Sim'
            }
         ]
      }
   ]
}

Code:

import json
import requests
import csv
import collections

url = 
headers = {'Content-Type' : 'application/json', 

} 

response = requests.get(url, headers=headers) 

res = json.loads(response.text)

output = []

for c in res['response']:
     goods = []
     if len(c['policies']) > 0:
         goods = [good["Nome"] for good in c['policies'] [0]['covered_goods']]

     output.append(goods)


d = {x:goods.count(x) for x in goods}
print(d)


print(output)

1 answer

1


Your iteration is not suitable for your output. When you count the output to put in d, will only have the result of the last iterated contract. Then we will make some modifications:

output = []

for c in res['response']: # trocar c por contract pra ficar mais fácil de entender
     goods = [] # remover essa variável que não será mais necessária
     if len(c['policies']) > 0:
         goods = [good["Nome"] for good in c['policies'] [0]['covered_goods']]   
     output.append(goods) # alocar a linha de cima direto em output

d = {x:output.count(x) for x in output}

Here is the code with the fixes. It goes through all the chips present in all the contracts and allocates the name to output:

output = []

for contract in res['response']: # tomei a liberdade de mudar o nome da variável
 if len(contract['policies']) > 0:
     for policy in contract['policies']: # tem que iterar aqui também!
         for profile in policy['covered_goods']:
             if 'Nome' in profile.keys():
                 output.append(profile['Nome'])

d = {x:output.count(x) for x in output}

At the end, where you put print(d), place:

for k,v in d.items():
    print(k,v)

Your return will be clean, with no component beyond the given:

Rex 2

In that code, k is the value of the dictionary’s key, which is actually the field Nome of its file, and v is the value of the dictionary, which is actually the count that you did. It is also possible for you to display something more elaborate like:

Rex: 2

for k,v in d.items():
    print(k,': ',v, sep='')

You can also store this in a string in this format:

string = [k+': '+str(v)+'\n' for k,v in d.items()]
string = ''.join(string)        
print(string)
  • Hey... thanks for answering, I tried but he takes the value of the last item, in case it was a dog named 'dog', like, he ignores the others...

  • I know what happens. I’ll help you.

  • I made the modifications based on what you said. If you have anything else, I suggest you even change the question in case someone else tries to help.

  • Hi, gave error: Typeerror: string indices must be integers.. already searched but could not fix...

  • I had removed the variable index res['response'] to simulate here on my computer. I returned it to the code and you can try again. From now on I cannot help you with the information you have given me. Why? Because I would need to know what the structure of your variable is like res. The part you sent relates only to the structure of a contract.

  • One thing that caught my attention is the fact that you put c['policies'][0]. Can I only have one policy in each contract? If you can have more, you have to iterate there as well.

  • My Deusss, it worked.... I think I understand your scores, I’ll study them all! Gratitude!

  • 1

    Glad it worked! Tell you that was the first time I put my hand on a JSON! Oh, and don’t forget to mark the answer as chosen! ;)

  • How do I do it ? Hahahaha

  • Next to the answers given, near where there is an arrow up and an arrow down, there is a V in the color gray. When you mark it, it turns green. Here shows how and here explains why to do this.

Show 5 more comments

Browser other questions tagged

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