如何写入读取yaml,json文件

# coding=utf-8
from ruamel import yaml
import json

"""
    /*
    @:param
    version python3.7
    python -m pip install ruamel.yaml
    
python None===>>json null
python True===>>json true
    */
"""


"""
    /*

    @param:
    @yaml.dump()
    @Dumper=yaml.RoundTripDumper,@default_flow_style=False,@allow_unicode=True
    @param: @yaml.load()
    @Loader=yaml.Loader
        method:
        write json file method
        read  json file method
    */
"""
data={
    "json": None,
    "method": "get",
    "data": {"id": 1001,"status": True,"CddL":{"jobName": "Job_pipeName","elapsedTime": "0.43"}},
    "header": {"Content-Type": "application/json"},
    "url": "http://www.huawei.com"
}


class Yml(object):
    def __init__(self, yml_path, data):
        self.yml_path = yml_path
        self.data = data

    def write(self, ):
        with open(self.yml_path, 'w', encoding='utf-8')as e:
            yaml.dump(self.data, e,Dumper=yaml.RoundTripDumper,default_flow_style=False,allow_unicode=True,indent=4)

    def read(self):
        with open(self.yml_path, 'r', encoding='utf-8')as f:
            data = yaml.load(f,Loader=yaml.Loader)
        return data

"""
    /*
    @param:
    @json.dump(),@json.load()
    write json file method
    read  json file method
   */
"""
class Js(object):
    def __init__(self, json_path, data):
        self.json_path = json_path
        self.data = data

    def write(self):
        with open(self.json_path, 'w', encoding='utf-8')as e:
            json.dump(self.data, e, ensure_ascii=False, separators=(',', ':'), indent=4)

    def read(self):
        with open(self.json_path, 'r', encoding='utf-8')as f:
            data = json.load(f)
            return data

if __name__ == "__main__":
    Yml('./conf.yaml',data).write()
    d=Yml('./conf.yaml',data).read()
    print(json.dumps(d,ensure_ascii=False,separators=(',', ':'), indent=4))
    Js('./config.json',data).write()
    t=Js('./config.json',data).read()
    print(json.dumps(t,ensure_ascii=False,separators=(',', ':'), indent=4))

 

C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/pytestframe/API/Jsread.py
{
    "json":null,
    "method":"get",
    "data":{
        "id":1001,
        "status":true,
        "cddl":{
            "jobName":"Job_pipeName",
            "elapsedTime":"0.43"
        }
    },
    "header":{
        "Content-Type":"application/json"
    },
    "url":"http://www.huawei.com"
}
{
    "json":null,
    "method":"get",
    "data":{
        "id":1001,
        "status":true,
        "cddl":{
            "jobName":"Job_pipeName",
            "elapsedTime":"0.43"
        }
    },
    "header":{
        "Content-Type":"application/json"
    },
    "url":"http://www.huawei.com"
}

Process finished with exit code 0

我的pycharm是专业版5.4展示yaml与社区版commuity不同不要奇怪,花钱的和免费的你懂得功能都相同就行了可读性更强
如何写入读取yaml,json文件_第1张图片

 

如何写入读取yaml,json文件_第2张图片

如何写入读取yaml,json文件_第3张图片

你可能感兴趣的:(接口测试)