简体   繁体   English

遍历Swagger YAML文件以动态生成属性列表

[英]Iterating over Swagger YAML File to dynamically generate a list of properties

I am trying to create a script that can accept a swagger yml file (like the example petstore.yaml), and generate a list of used "attributes" from the file. 我正在尝试创建一个脚本,该脚本可以接受一个庞大的yml文件(例如示例petstore.yaml),并从该文件生成使用的“属性”列表。

This involves the parsing of yaml, then iterating over all elements in the json object to return the required data. 这涉及到yaml的解析,然后遍历json对象中的所有元素以返回所需的数据。 I intend to traverse all the paths to identify valid responses, but for now I just want to filter out all definitions specified in the yaml file, then for each def, output the list of properties. 我打算遍历所有路径以标识有效的响应,但是现在我只想过滤掉yaml文件中指定的所有定义,然后为每个def输出属性列表。

a sample yaml file can be downloaded here 可以在此处下载示例yaml文件

at the end of the day, i would like to generate a string for each attribute which shows something like 在一天结束时,我想为每个属性生成一个字符串,该字符串显示如下内容

<filename>~Pet~id~integer~int64
<filename>~Pet~name~string~
<filename>~Pet~tag~string~

for this, i need to locate the 'definitions' node, and iterate over all sub-nodes to read the info. 为此,我需要找到“ definitions”节点,并遍历所有子节点以读取信息。

I am struggling to get the logic right for a yaml styled file.. Below is my working code. 我正在努力为yaml样式的文件弄清楚逻辑。.下面是我的工作代码。

It just feels to me like I have over-complicated the iterative looping (maybe a better solution would be to use regex? 感觉就像是我使迭代循环过于复杂(也许更好的解决方案是使用正则表达式?

index.html 的index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>Read YAML</title>
        </script><script src='https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js'>            
    </script>
    <body>
        <input type="file" id="file-input" />
        <h3>Contents of the file:</h3>
        <pre id="file-content"></pre>
        <div id='output'></div>
    </body>
    <script>
        var yaml = window.jsyaml;
        </script>
    <script src="app.js"></script>
</html>

my javascript file 我的javascript文件

var body = '';
var mystring = '' 
function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
      var contents = e.target.result;
      displayContents(contents);
    };
    reader.readAsText(file);
}

function displayContents(contents) {
      var element = document.getElementById('file-content');
      var doc = yaml.load(contents);
      // Process the file.
      // Process only the definitions section of the file
      var definition = doc.definitions
      console.log (definition) ;
      for(var def in definition) {
        if(definition.hasOwnProperty(def)) {
          var node = definition[def]
            if (typeof(node) === 'object') {
                // loop through the definitions
                processContents(node)
            }
        }
      }

      function processContents(obj) {
        for (var item in obj) {
              var definitions = obj[item]
              if (typeof definitions === 'object'){
                for (var attribute in definitions) {
                  // HELP -- if there is an attribute called "properties"  then iterate over all properties and create the concatenated string
                  // Broken from here !!!!
                  if (attribute.properties) {
                      for (var param  in attribute.properties) {
                        mystring = param.name + '~' + param.type + '~' + param.description + '~' + param.format
                      }
                  }
              }
              }
        }

      }
      document.getElementById('output').innerHTML = body;
 }

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

I am running out of time so I will leave it here. 我没时间了,所以我把它留在这里。 It's not as refined as it is but I hope it helps you. 它虽然不够精致,但希望对您有所帮助。

So I did a recursive function to iterate through the objects. 所以我做了一个递归函数来遍历对象。 The function takes in an object and a prefix. 该函数接受一个对象和一个前缀。 The prefix will be used for printing the details. 该前缀将用于打印细节。 The exclude prefixes is used to not show certain field names and the exclude types is to not print certain types. 排除前缀用于不显示某些字段名称,排除类型用于不打印某些类型。 Loop through the fields of an object an catch format, type, description and whatever you want to catch. 在对象的字段中循环显示捕获格式,类型,描述以及您要捕获的任何内容。 When done looping the fields of an object check if the type field is populated. 完成循环后,检查对象的字段是否填充了type字段。 If it is then log the parameter details. 如果是,则记录参数详细信息。

var body = '';
var mystring = '' 
function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
      var contents = e.target.result;
      displayContents(contents);
    };
    reader.readAsText(file);
}

function displayContents(contents) {
      console.log('---contents---')
      console.log(contents)
      var element = document.getElementById('file-content');
      console.log('---element----')
      console.log(element)
      var doc = yaml.load(contents);
      console.log('---doc')
      console.log(doc)
      // Process the file.
      // Process only the definitions section of the file
      var definition = doc.definitions
      console.log('---definition---')
      console.log (definition) ;

    processContents2(doc.definitions)

    function processContents2(obj, prefix) {
        const excludePrefixes = ['properties']
        const excludeTypes = ['object', 'array']
        let format = ''
        let type = ''
        let description = ''
        let count = 0;
        for (var field in obj) {
            if (typeof obj[field] === 'object') {
                processContents2(obj[field], (prefix || '') + (excludePrefixes.indexOf(field) === -1 ? '~' + field : ''))
            } else {
                if (field === 'format') {
                    format = obj[field]
                } else if (field === 'type') {
                    type = obj[field]
                } else if (field === 'description') {
                    description = obj[field]
                }
            }
        }
        if (type && (excludeTypes.indexOf(type) === -1)) {
            console.log((prefix || '') + '~' + type  + (description ? '~' + description : '') + (format ? '~' + format : ''))
        } 
      }

      document.getElementById('output').innerHTML = body;
 }

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM