json_util.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 parse_json_from_string(input_str):
  37. result = [] # 存储成功解析的 JSON 对象
  38. stack = [] # 栈,用于追踪 '{'
  39. temp_str = "" # 临时存储 JSON 字符串
  40. for i, char in enumerate(input_str):
  41. temp_str += char
  42. if char == '{':
  43. stack.append(char)
  44. elif char == '}':
  45. if stack:
  46. stack.pop() # 配对成功一个 '{'
  47. # 检查栈是否为空,表示一个完整的 JSON 片段
  48. if not stack:
  49. try:
  50. parsed_json = json.loads(temp_str)
  51. result.append(parsed_json)
  52. temp_str = "" # 清空临时字符串
  53. except json.JSONDecodeError:
  54. # 解析失败,可能是嵌套不完整,继续累积字符
  55. pass
  56. return result
  57. def find_key(data, target_key):
  58. if isinstance(data, dict):
  59. # 如果是字典,递归查找每个键
  60. for key, value in data.items():
  61. if key == target_key:
  62. return value
  63. result = find_key(value, target_key)
  64. if result:
  65. return result
  66. elif isinstance(data, list):
  67. # 如果是列表,递归查找每个元素
  68. for item in data:
  69. result = find_key(item, target_key)
  70. if result:
  71. return result
  72. return None