python读取json文件

作者: 萝卜枣 | 来源:发表于2021-10-09 10:00 被阅读0次
import json
import os
from pathlib import Path


class JsonConf:
    def __init__(self, file_path='server', json_conf='conf.json'):
        self.json = None
        self._exec(file_path, json_conf)

    def _exec(self, path, conf):
        """读取json文件"""
        if Path(path).is_absolute():
            conf_path = Path(conf)
        else:
            # 获取当前运行脚本的绝对路径
            dir_path = os.path.dirname(__file__)
            print("----", dir_path)  # /Users/dingyuanlin/Desktop/code/dyl_demo
            print("----", path)  # script_json
            print("----", conf)  # register.json
            conf_path = Path().joinpath(dir_path, path,
                                        conf)  # /Users/dingyuanlin/Desktop/code/dyl_demo/script_json/register.json
        with conf_path.open(encoding='utf-8') as conf:    # with…as语句是简化版的try except finally语句。
            # json.loads:对数据进行解码
            self.json = json.loads(conf.read())

    def globals(self, key=None):
        if key is None:
            value = self.json #demo走这里了
        else:
            try:
                value = self.json[key]
            except KeyError as e:
                raise e
        return value


#调用的地方
conf = JsonConf(file_path="script_json", json_conf="register.json")
headers = conf.globals()["headers"]
print(headers)                   # {'cache-control': 'no-cache', 'content-type': 'application/x-www-form-urlencoded', 'postman-token': '3f8e3795-b71e-1a41-504b-a8197f34c91d'}
print(headers['cache-control'])  # no-cache


#register.json的具体内容
"""
{
  "headers":
  {
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded",
    "postman-token": "3f8e3795-b71e-1a41-504b-a8197f34c91d"
  },
  "body":
  {
    "username": "7888"
  }
}
"""

相关文章

网友评论

    本文标题:python读取json文件

    本文链接:https://www.haomeiwen.com/subject/dreogltx.html