Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Json when the key is unknown using Python?

Tags:

python

json

This is a sample of my Json:

text = {"rates":{
   "AT":{
     "country_name":"Austria",
     "standard_rate":20,
     "reduced_rates":{
       "food":10,
       "books":10
     }
  }
}}

Now the "AT" is the country code.. It's not fixed. It can also be GB, IT etc...

I want to parse this Json and get from it columns as follow:

rates.AT   rates.AT.country_name   rates.AT.reducted_rates.food
  AT           Austria                  10

Can be also renamed to:

code        country_name               food
  AT           Austria                  10

Say for example that in another run I have:

text = {"rates":{
   "IT":{
     "country_name":"Italy",
     "standard_rate":20,
     "reduced_rates":{
       "food":13,
       "books":11
     }
  }
}}

Then It needs to be:

rates.IT   rates.IT.country_name   rates.IT.reducted_rates.food
  IT           Italy                     13

Can be also renamed to:

 code        country_name               food
  IT           Italy                     13

How can I do this?

EDIT:

If possible using @GPhilo answer I would prefer to get the data as Pandas dataframe. Something like?

df = pd.DataFrame()
for k,item in dic['rates'].items(): # use iteritems() if you're on Python 2
    line = '{};{};{}'.format(k, item['country_name'], item['reduced_rates']['food'])
    df = df.append(line, ignore_index=True)

This doesn't work because line isn't the proper way to do this.

like image 486
Luis Avatar asked Feb 11 '26 20:02

Luis


1 Answers

Once parsed, json objects are python dicts, so just loop over the key/value pair at the level you need and print the information:

import json

dic = json.loads('''
{"rates":{
   "AT":{
     "country_name":"Austria",
     "standard_rate":20,
     "reduced_rates":{
       "food":10,
       "books":10
     }
  }
}}
''')

for k,item in dic['rates'].items(): # use iteritems() if you're on Python 2
    print('{};{};{}'.format(k, item['country_name'], item['reduced_rates']['food']))

Format the output as needed, the three values you need are the three in the format call in the code above. Running the sample returns:

AT;Austria;10

Edit: Amended the answer

Once parsed, json objects are python dicts: print(dic.__class__) returns <class 'dict'>.

Update

In reply to the edit in the question, instead of appending the formatted string, just append the values:

df = pd.Dataframe(columns=['code', 'country_name', 'food'])
[...]
df = df.append([k, item['country_name'], item['reduced_rates']['food']], ignore_index=True)
like image 144
GPhilo Avatar answered Feb 13 '26 08:02

GPhilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!