Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import re
  2. import warnings
  3.  
  4.  
  5. def convert_string_to_snake_case(s):
  6. """
  7. Changes String to from camelCase to snake_case
  8. :param s: String to convert
  9. :rtype: String
  10. :rertuns: String converted to snake_case
  11. """
  12. a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
  13. return a.sub(r'_\1', s).lower()
  14.  
  15.  
  16. def convert_list_to_snake_case(a):
  17. """
  18. Iterates over a list and changes the key values
  19. from camelCase to snake_case
  20. :param a: List of dictionaries to convert
  21. :rtype: list
  22. :rertuns: list with each key converted to snake_case
  23. """
  24. new_arr = []
  25. for i in a:
  26. new_arr.append(convert_object_to_snake_case(i))
  27. return new_arr
  28.  
  29.  
  30. def convert_dict_to_snake_case(d):
  31. """
  32. Iterates over a dictionary and changes the key values
  33. from camelCase to snake_case
  34. :param d: Dictionary to convert
  35. :rtype: dict
  36. :rertuns: dictionary with each key converted to snake_case
  37. """
  38. out = {}
  39. for k in d:
  40. new_k = convert_string_to_snake_case(k)
  41. out[new_k] = convert_object_to_snake_case(d[k])
  42. return out
  43.  
  44.  
  45. def convert_object_to_snake_case(o):
  46. """
  47. Iterates over an object and changes the key values
  48. from camelCase to snake_case
  49. :param o: Dictionary or Array of dictionaries to convert
  50. :rtype: o
  51. :rertuns: Same type that was passed
  52. """
  53. if isinstance(o, list):
  54. return convert_list_to_snake_case(o)
  55. elif isinstance(o, dict):
  56. return convert_dict_to_snake_case(o)
  57. elif isinstance(o, str):
  58. return convert_string_to_snake_case(o)
  59. else:
  60. warning = "Type: " + type(o).__name__ + " is not supported to convert to snake_case"
  61. warnings.warn(warning, Warning)
  62. return o
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement