12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- """
- 自定义的一些 json功能
- """
- import 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
- def parse_json_from_string(input_str):
- result = [] # 存储成功解析的 JSON 对象
- stack = [] # 栈,用于追踪 '{'
- temp_str = "" # 临时存储 JSON 字符串
- for i, char in enumerate(input_str):
- temp_str += char
- if char == '{':
- stack.append(char)
- elif char == '}':
- if stack:
- stack.pop() # 配对成功一个 '{'
- # 检查栈是否为空,表示一个完整的 JSON 片段
- if not stack:
- try:
- parsed_json = json.loads(temp_str)
- result.append(parsed_json)
- temp_str = "" # 清空临时字符串
- except json.JSONDecodeError:
- # 解析失败,可能是嵌套不完整,继续累积字符
- pass
- return result
- def find_key(data, target_key):
- if isinstance(data, dict):
- # 如果是字典,递归查找每个键
- for key, value in data.items():
- if key == target_key:
- return value
- result = find_key(value, target_key)
- if result:
- return result
- elif isinstance(data, list):
- # 如果是列表,递归查找每个元素
- for item in data:
- result = find_key(item, target_key)
- if result:
- return result
- return None
|