如何从python中的嵌套YAML文件中读取数据?

问题描述 投票:0回答:2

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

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

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
2个回答
0
投票

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

对于该安装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']

0
投票

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

得到例如名称值(“ body”):

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

结果:

>>> body 
© www.soinside.com 2019 - 2024. All rights reserved.