【问题标题】:How to read data from nested YAML file in python?如何从 python 中的嵌套 YAML 文件中读取数据?
【发布时间】:2020-07-05 13:56:24
【问题描述】:

我有例如 swagger.yaml 文件,我想从中读取一些变量。 例如那个文件:https://editor.swagger.io/

下面是文件片段。 有可能得到例如。 “参数”的值?最好将它们分配给一些变量。

paths:
  /pet:
    post:
      tags:
      - "pet"
      summary: "Add a new pet to the store"
      description: ""
      operationId: "addPet"
      consumes:
      - "application/json"
      - "application/xml"
      produces:
      - "application/xml"
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "Pet object that needs to be added to the store"
        required: true
        schema:
          $ref: "#/definitions/Pet"
      responses:
        405:
          description: "Invalid input"
      security:
      - petstore_auth:
        - "write:pets"
        - "read:pets"

我有那个代码:

import yaml

path_to_yaml = '../data/swagger.yaml'

with open(path_to_yaml) as f:
    dataMap = yaml.safe_load(f)
print(yaml.dump(dataMap, default_flow_style=False))

【问题讨论】:

    标签: python python-3.x yaml pyyaml


    【解决方案1】:

    考虑使用字典来访问参数的值。

    为此安装PyYAML

    import yaml
    yaml_as_python_dict = yaml.load(yaml_as_string_or_bytes)
    

    然后就是简单地通过键来获取值

    例如,

    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    print "dict['Name']: ", dict['Name']
    print "dict['Age']: ", dict['Age']
    

    【讨论】:

    • 还要注意,它确实有在不受控制的 YAML 输入上失败的趋势。为此,您可以使用this,它可以有效地完成相同的工作。但是,再次由您来决定。
    【解决方案2】:

    我通过安装scalpl 解决了这个问题 https://yaml.readthedocs.io/en/latest/install.html

    得到例如。名称值(“正文”):

    with open(file.yaml) as f:
        dataMap = yaml.safe_load(f)
    proxy = Cut(dataMap)
    print(proxy['paths.pet.post.parameters.name']
    

    结果:

    >>> body 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2020-07-17
      • 1970-01-01
      • 2021-12-01
      • 2020-01-28
      • 2022-01-20
      • 1970-01-01
      • 2019-01-09
      相关资源
      最近更新 更多