json_conf.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2022/05/24 15:07:14
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : yaml util
  8. '''
  9. import os
  10. import json
  11. class JsonConf:
  12. def __init__(self, config_path="conf/config.json"):
  13. self.config_path = config_path
  14. self.data=None
  15. self.load()
  16. def save(self, data):
  17. with open(self.config_path, 'w') as json_file:
  18. json_file.write(json.dumps(data, indent=4))
  19. def load(self):
  20. if not os.path.exists(self.config_path):
  21. with open(self.config_path, 'w') as json_file:
  22. pass
  23. with open(self.config_path, encoding="utf-8") as json_file:
  24. try:
  25. self.data = json.load(json_file)
  26. except Exception as e:
  27. if(str(e).index("utf-8-sig") > 0):
  28. with open(self.config_path, encoding="utf-8-sig") as json_file:
  29. self.data = json.load(json_file)
  30. return self
  31. else:
  32. print(e)
  33. return self
  34. def set(self, data_dict):
  35. json_obj = self.load().data
  36. for key in data_dict:
  37. json_obj[key] = data_dict[key]
  38. self.save(json_obj)
  39. def get(self, key, default_val=""):
  40. '''
  41. 配置文件获取key对象的值,如果没有设置就返回默认值
  42. '''
  43. try:
  44. result = self.load().data[key]
  45. return result
  46. except Exception as e:
  47. print(e)
  48. return default_val
  49. def get(self, jsonData, key, default_val=""):
  50. try:
  51. return jsonData[key]
  52. except Exception as e:
  53. return default_val
  54. @staticmethod
  55. def get(jsonData, key, default_val=""):
  56. try:
  57. return jsonData[key]
  58. except Exception as e:
  59. return default_val