json_util.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """
  2. 自定义的一些 json功能
  3. """
  4. import json
  5. import re
  6. def underscore_to_camelcase(snake_str):
  7. """ 将下划线命名转换为驼峰命名 """
  8. components = snake_str.split('_')
  9. return components[0] + ''.join(x.title() for x in components[1:])
  10. def camelcase_to_underscore(camel_str):
  11. """将驼峰命名转换为下划线命名"""
  12. return re.sub(r'(?<!^)(?=[A-Z])', '_', camel_str).lower()
  13. def convert_keys_to_camelcase(obj):
  14. """ 递归处理 JSON 对象 """
  15. if isinstance(obj, dict):
  16. new_obj = {}
  17. for k, v in obj.items():
  18. new_key = underscore_to_camelcase(k)
  19. new_obj[new_key] = convert_keys_to_camelcase(v)
  20. return new_obj
  21. elif isinstance(obj, list):
  22. return [convert_keys_to_camelcase(item) for item in obj]
  23. else:
  24. return obj
  25. def convert_keys_to_underscore(obj):
  26. if isinstance(obj, dict):
  27. new_obj = {}
  28. for k, v in obj.items():
  29. new_key = camelcase_to_underscore(k)
  30. new_obj[new_key] = convert_keys_to_underscore(v)
  31. return new_obj
  32. elif isinstance(obj, list):
  33. return [convert_keys_to_underscore(item) for item in obj]
  34. else:
  35. return obj
  36. def get_json_from_content(content:str, key:str):
  37. """
  38. 从不规则的长字符中解析出想要的 json文件
  39. :param content:
  40. :param key 想要获得的 key
  41. :return:
  42. """
  43. inside_items = False # 标志是否进入 items 部分
  44. items_buffer = "" # 临时保存 JSON 部分
  45. for line in content.splitlines():
  46. # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
  47. line = line.strip() # 去掉多余的空白字符
  48. if f'"${key}"' in line:
  49. items_buffer = '{'
  50. inside_items = True # 发现目标字段
  51. continue
  52. # 处理 items 数组的部分
  53. if inside_items:
  54. items_buffer += line # 累积读取多行
  55. # 如果找到了 JSON 数组的结束
  56. if '"items": [' in items_buffer and ']' in items_buffer:
  57. try:
  58. # 尝试解析 JSON
  59. data = json.loads(items_buffer)
  60. # 获取第一个 item
  61. return data
  62. except json.JSONDecodeError:
  63. continue # 如果解析失败,继续读取下一行
  64. return None # 如果没有找到匹配项
  65. def find_key(data, target_key):
  66. if isinstance(data, dict):
  67. # 如果是字典,递归查找每个键
  68. for key, value in data.items():
  69. if key == target_key:
  70. return value
  71. result = find_key(value, target_key)
  72. if result:
  73. return result
  74. elif isinstance(data, list):
  75. # 如果是列表,递归查找每个元素
  76. for item in data:
  77. result = find_key(item, target_key)
  78. if result:
  79. return result
  80. return None