DEV Community

Santhosh Thomas
Santhosh Thomas

Posted on

Convert Keys in Json to Snake Case

import re

def convert_to_snakecase(original_dict):

    transformed_dict = {}
    array_items = []
    if not isinstance(original_dict, list):
      for k in original_dict.keys():
          value = re.sub(r'(?<!^)(?=[A-Z])', '_', k).lower()
          if not isinstance(original_dict[k], list):
              if isinstance(original_dict[k], dict):
                  transformed_dict[value] = convert_to_snakecase(original_dict[k])
              else:
                  transformed_dict[value] = original_dict[k]
          else: 

              array_items = []
              for i in range(len(original_dict[k])):
                  if isinstance(original_dict[k][i], dict):
                      array_items.append(convert_to_snakecase(original_dict[k][i]))
                      transformed_dict[value] =  array_items
                  else:
                      transformed_dict[value] = original_dict[k]
    else:
        array_items = []
        for item in original_dict:
          array_items.append(convert_to_snakecase(item))
        transformed_dict.update(array_items)
    return transformed_dict

Enter fullscreen mode Exit fullscreen mode

Top comments (0)