1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- """
- 自定义的一些 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 get_json_from_content(content:str, key:str):
- """
- 从不规则的长字符中解析出想要的 json文件
- :param content:
- :param key 想要获得的 key
- :return:
- """
- inside_items = False # 标志是否进入 items 部分
- items_buffer = "" # 临时保存 JSON 部分
- for line in content.splitlines():
- # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
- line = line.strip() # 去掉多余的空白字符
- if f'"${key}"' in line:
- items_buffer = '{'
- inside_items = True # 发现目标字段
- continue
- # 处理 items 数组的部分
- if inside_items:
- items_buffer += line # 累积读取多行
- # 如果找到了 JSON 数组的结束
- if '"items": [' in items_buffer and ']' in items_buffer:
- try:
- # 尝试解析 JSON
- data = json.loads(items_buffer)
- # 获取第一个 item
- return data
- except json.JSONDecodeError:
- continue # 如果解析失败,继续读取下一行
- return None # 如果没有找到匹配项
- 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
|