xpickle.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # update: 2021-6-30-11
  2. import pickle
  3. import json
  4. def pickle_dumps(obj):
  5. """压缩数据"""
  6. return pickle.dumps(obj)
  7. def pickle_loads(obj):
  8. """解压数据"""
  9. return pickle.loads(obj)
  10. def json_dumps(obj):
  11. """压缩数据"""
  12. return json.dumps(obj)
  13. def json_loads(obj):
  14. """解压数据"""
  15. return json.loads(obj)
  16. def is_json(string):
  17. """是否json"""
  18. try:
  19. if string:
  20. json.loads(string)
  21. else:
  22. return False
  23. except Exception as exception:
  24. return False
  25. return True
  26. def str_to_re(string):
  27. """
  28. 转义正则特殊符号
  29. """
  30. string = string.replace('$', r'\$')
  31. string = string.replace('(', r'\(')
  32. string = string.replace(')', r'\)')
  33. string = string.replace('*', r'\*')
  34. string = string.replace('.', r'\.')
  35. string = string.replace('[', r'\[')
  36. string = string.replace(']', r'\]')
  37. string = string.replace('?', r'\?')
  38. string = string.replace('\\', '\\\\')
  39. string = string.replace('^', r'\^')
  40. string = string.replace('{', r'\{')
  41. string = string.replace('}', r'\}')
  42. string = string.replace('|', r'\|')
  43. return string
  44. def str_to_json(string):
  45. """
  46. eval转换
  47. """
  48. null = None
  49. true = True
  50. false = False
  51. return eval(string)
  52. def json_to_str(input_data):
  53. """
  54. eval转换
  55. """
  56. if type(input_data) == dict:
  57. for k, v in input_data.items():
  58. if type(v) != str:
  59. continue
  60. input_data[k] = v.replace('\'', '')
  61. data = str(input_data).replace('\'', '\"')
  62. data = str(data).replace('None', 'null')
  63. data = str(data).replace('True', 'true')
  64. data = str(data).replace('False', 'false')
  65. return data
  66. if __name__ == '__main__':
  67. # --- test ---
  68. # a = {111: 222}
  69. # print(json_dumps(a))
  70. # print(json_loads(json_dumps(a)))
  71. # --- test ---
  72. a = b'\x80\x03N.'
  73. o = pickle_loads(a)
  74. print(o, type(o))