json_conf.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. def save(self, data):
  15. with open(self.config_path, 'w') as json_file:
  16. json_file.write(json.dumps(data, indent=4))
  17. def load(self):
  18. if not os.path.exists(self.config_path):
  19. with open(self.config_path, 'w') as json_file:
  20. pass
  21. with open(self.config_path, encoding="utf-8") as json_file:
  22. try:
  23. data = json.load(json_file)
  24. except Exception as e:
  25. if(str(e).index("utf-8-sig") > 0):
  26. with open(self.config_path, encoding="utf-8-sig") as json_file:
  27. data = json.load(json_file)
  28. return data
  29. else:
  30. print(e)
  31. return data
  32. def set(self, data_dict):
  33. json_obj = self.load()
  34. for key in data_dict:
  35. json_obj[key] = data_dict[key]
  36. self.save(json_obj)
  37. print(json.dumps(json_obj, indent=4))
  38. def get(self, key, default_val=""):
  39. '''
  40. 配置文件获取key对象的值,如果没有设置就返回默认值
  41. '''
  42. try:
  43. result = self.load()[key]
  44. return result
  45. except Exception as e:
  46. print(e)
  47. return default_val
  48. def get(self, jsonData, key, default_val=""):
  49. try:
  50. return jsonData[key]
  51. except Exception as e:
  52. return default_val
  53. @staticmethod
  54. def get(jsonData, key, default_val=""):
  55. try:
  56. return jsonData[key]
  57. except Exception as e:
  58. return default_val