Home > Back-end >  Is it possible to rename a json key name using its value in Python?
Is it possible to rename a json key name using its value in Python?

Time:12-02

I have this nested json dictionary and I want to rename the key name 'Keys' with its equivalent value using Python. I wonder if this is possible?

Current - 'Keys': ['AWS Backup'] I want it to be - 'AWS Backup': ['AWS Backup']

Sample json dictionary {'TimePeriod': {'Start': '2022-11-28', 'End': '2022-11-29'}, 'Total': {}, 'Groups': [{'Keys': ['AWS Backup'], 'Metrics': {'UnblendedCost': {'Amount': '0.000000111', 'Unit': 'USD'}}}, {'Keys': ['AWS Direct Connect'], 'Metrics': {'UnblendedCost': {'Amount': '0.0000111', 'Unit': 'USD'}}}, {'Keys': ['AWS Key Management Service'], 'Metrics': {'UnblendedCost': {'Amount': '0.000000111', 'Unit': 'USD'}}}

Tried do flatten the json but after doing it still no luck. I'm not sure if I can do it using pandas dataframe also? Plan to save that json also in a csv file.

CodePudding user response:

Yes, it is possible to rename a JSON key name using its value in Python. Here is an example of how you can do this using the json module:

import json

# Original JSON dictionary
data = {
    'TimePeriod': {'Start': '2022-11-28', 'End': '2022-11-29'},
    'Total': {},
    'Groups': [
        {'Keys': ['AWS Backup'],
         'Metrics': {
             'UnblendedCost': {
                 'Amount': '0.000000111',
                 'Unit': 'USD'
             }
         }
        },
        {'Keys': ['AWS Direct Connect'],
         'Metrics': {
             'UnblendedCost': {
                 'Amount': '0.0000111',
                 'Unit': 'USD'
             }
         }
        },
        {'Keys': ['AWS Key Management Service'],
         'Metrics': {
             'UnblendedCost': {
                 'Amount': '0.000000111',
                 'Unit': 'USD'
             }
         }
        }
    ]
}

# Loop through each group and rename the 'Keys' key with its value
for group in data['Groups']:
    key = group['Keys'][0]
    group[key] = group.pop('Keys')

# Print the updated JSON dictionary
print(json.dumps(data, indent=2))

The output will be:

{
  "TimePeriod": {
    "Start": "2022-11-28",
    "End": "2022-11-29"
  },
  "Total": {},
  "Groups": [
    {
      "AWS Backup": [
        "AWS Backup"
      ],
      "Metrics": {
        "UnblendedCost": {
          "Amount": "0.000000111",
          "Unit": "USD"
        }
      }
    },
    {
      "AWS Direct Connect": [
        "AWS Direct Connect"
      ],
      "Metrics": {
        "UnblendedCost": {
          "Amount": "0.0000111",
          "Unit": "USD"
        }
      }
    },
    {
      "AWS Key Management Service": [
        "AWS Key Management Service"
      ],
      "Metrics": {
        "UnblendedCost": {
          "Amount": "0.000000111",
          "Unit": "USD"
        }
      }
    }
  ]
}
  • Related