123456789101112131415161718192021222324252627282930313233343536373839404142 |
- """
- 自定义的一些 json功能
- """
- import re
- def underscore_to_camelcase(snake_str):
- """ 将下划线命名转换为驼峰命名 """
- components = snake_str.split('_')
- return components[0] + ''.join(x.title() for x in components[1:])
- def camelcase_to_underscore(camel_str):
- """将驼峰命名转换为下划线命名"""
- return re.sub(r'(?<!^)(?=[A-Z])', '_', camel_str).lower()
- def convert_keys_to_camelcase(obj):
- """ 递归处理 JSON 对象 """
- if isinstance(obj, dict):
- new_obj = {}
- for k, v in obj.items():
- new_key = underscore_to_camelcase(k)
- new_obj[new_key] = convert_keys_to_camelcase(v)
- return new_obj
- elif isinstance(obj, list):
- return [convert_keys_to_camelcase(item) for item in obj]
- else:
- return obj
- def convert_keys_to_underscore(obj):
- if isinstance(obj, dict):
- new_obj = {}
- for k, v in obj.items():
- new_key = camelcase_to_underscore(k)
- new_obj[new_key] = convert_keys_to_underscore(v)
- return new_obj
- elif isinstance(obj, list):
- return [convert_keys_to_underscore(item) for item in obj]
- else:
- return obj
|