3

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.

5
  • I understand that the key each time is unknown, but do you have a collections of keys? For example, "IT" for Italy, "US" for USA, "RU" for Russia etc are known to you? Commented Jan 22, 2019 at 10:24
  • __import__('json').loads(your_json_string) Commented Jan 22, 2019 at 10:27
  • What do you mean by time? The sample of data is what I get from the Json I just need to convert it to insert to columns in my DB Commented Jan 22, 2019 at 10:27
  • @karansthr print (json.loads(text)) gives TypeError: the JSON object must be str, not 'dict' converting to string doesn't work either Commented Jan 22, 2019 at 10:29
  • you have to pass string not the dict Commented Jan 22, 2019 at 10:30

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Is it possible to do json.dumps instead of print?
The print is just to show the three values you need to use. You can use k, item['country_name'], item['reduced_rates']['food'] in any way you want, possibly manipulating them or formatting in a different way. If you update your answer with an example of how you want the output to be I can update the answer
TypeError: append() got an unexpected keyword argument 'columns'
sorry, the columns went in the Dataframe definition
I tried that it doesn't preduce the correct result all the code, country_name and food columns contains NaN and there is a 0 column with all the values
|
3

you should use dict.keys() to get a list of all keys of a dictionary, and then you can iterate it and do whatever you need with it. For example:

for k in text.keys():
   #do something with text[k] or k itself

consider also use dict.items() to get pairs of key, value:

for k, v in text.items():
    #do something with k and v, where text[k] is v

that's good for python 3, in python 2 you should use dict.iteritems()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.