Python Edit/Rename Key Names in .json

丶灬走出姿态 提交于 2020-01-13 06:35:08

问题


Is there a way to change the Key name? I need to change the name "Class123" like it is in the Example. I can change the Value but i dont know how to change the key name.

Example .json:

{
    "Class123": "classvalue", 
    "name1": {
        "name2": {
            "name3": {
                "Y": 158.8, 
                "X": 201.46
            }, 
            "name4": {
                "Y": 159.68, 
                "X": 200.32
            }
        }
    }
}

Starting like this:

    with open('my.json') as json1:
data = json.load(json1)
for item in data:

回答1:


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}



回答2:


Something like

your_dict[new_key] = your_dict.pop(old_key)

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




回答3:


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.



来源:https://stackoverflow.com/questions/49777924/python-edit-rename-key-names-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!