Python Edit/Rename Key Names in .json Python Edit/Rename Key Names in .json json json

Python Edit/Rename Key Names in .json


There is no way to "change" a key name.The best you can do is to copy the value to another key by using pop:

d = {'old_name': 1}d['new_name'] = d.pop('old_name')print(d)# {'new_name': 1}


I'd like to add my method here since it expands the singular naming to using a dict of keys.

Lets say you have a sample JSON list ga_list and you would like to change all the names with a dict key names_key :

names_key = { 'ga:date'            : 'date' ,              'ga:bounceRate'      : 'bounce' ,              'ga:newUsers'        : 'new_users',               'ga:pageviews'       : 'page_views',              'ga:sessions'        : 'sessions',              'ga:uniquePageviews' : 'unique_page_views',              'ga:users'           : 'users'              }ga_list = [{      'ga:bounceRate': 34.478408,      'ga:date': '20151203',      'ga:newUsers': 1679,      'ga:pageviews': 550,      'ga:sessions': 307,      'ga:uniquePageviews': 467,      'ga:users': 256},    {'ga:bounceRate': 21.28534,      'ga:date': '20151204',      'ga:newUsers': 164,      'ga:pageviews': 594,      'ga:sessions': 305,      'ga:uniquePageviews': 476,      'ga:users': 252},    {'ga:bounceRate': 13.8372346,      'ga:date': '20151205',      'ga:newUsers': 152,      'ga:pageviews': 826,      'ga:sessions': 330,      'ga:uniquePageviews': 241,      'ga:users': 200}]for row in ga_list:  for k, v in names_key.items():    for old_name in row:      if k == old_name:        row[v] = row.pop(old_name)print(ga_list)>>>[{'bounce': 34.47842608,  'date': '20151203',  'new_users': 1679,  'page_views': 550,  'sessions': 307,  'unique_page_views': 467,  'users': 256}, {'bounce': 21.28534,  'date': '20151204',  'new_users': 164,  'page_views': 594,  ....  'unique_page_views': 241,  'users': 200}]

And there you have it all the old names are renamed according to the key.

Hope this helps someone.


Something like

your_dict[new_key] = your_dict.pop(old_key)

Removing the old key from your dict and creating a new one.