json_util.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """
  2. 自定义的一些 json功能
  3. """
  4. import re
  5. def underscore_to_camelcase(snake_str):
  6. """ 将下划线命名转换为驼峰命名 """
  7. components = snake_str.split('_')
  8. return components[0] + ''.join(x.title() for x in components[1:])
  9. def camelcase_to_underscore(camel_str):
  10. """将驼峰命名转换为下划线命名"""
  11. return re.sub(r'(?<!^)(?=[A-Z])', '_', camel_str).lower()
  12. def convert_keys_to_camelcase(obj):
  13. """ 递归处理 JSON 对象 """
  14. if isinstance(obj, dict):
  15. new_obj = {}
  16. for k, v in obj.items():
  17. new_key = underscore_to_camelcase(k)
  18. new_obj[new_key] = convert_keys_to_camelcase(v)
  19. return new_obj
  20. elif isinstance(obj, list):
  21. return [convert_keys_to_camelcase(item) for item in obj]
  22. else:
  23. return obj
  24. def convert_keys_to_underscore(obj):
  25. if isinstance(obj, dict):
  26. new_obj = {}
  27. for k, v in obj.items():
  28. new_key = camelcase_to_underscore(k)
  29. new_obj[new_key] = convert_keys_to_underscore(v)
  30. return new_obj
  31. elif isinstance(obj, list):
  32. return [convert_keys_to_underscore(item) for item in obj]
  33. else:
  34. return obj