json - Powershell 解析 Swagger Json

标签 json powershell-7.0

以下工作将 Swagger json 解析为资源、方法、httptype,但可能... $path.Definition 部分很奇怪,我如何才能使 $path.Definition 成为一个数组而不是我需要的字符串解析数组符号。

$json = Get-Content -Path "$PSScriptRoot/Test/example_swagger.json" | ConvertFrom-Json
$paths = Get-Member -InputObject $json.paths -MemberType NoteProperty
$result = ""
foreach($path in $paths) {
    $elements = $path.Name.Substring(5).split("/") -join ","
    $httpmethods = $path.Definition.Substring($path.Definition.IndexOf("@{"))
    if ($httpmethods.Contains("get")) {
        $result += $elements + ", GET" + "`n"
    }
    if ($httpmethods.Contains("post")) {
        $result += $elements + ", POST" + "`n" #same methodnames different http methods
    }
}
$result

最佳答案

正如我对 Iterating through a JSON file PowerShell 的回答中所详细说明的,ConvertFrom-Json 的输出很难迭代。这使得“对于对象中的每个键”和“提前未知对象的键”这种情况更难以处理,但并非不可能。

您需要一个辅助函数:

# helper to turn PSCustomObject into a list of key/value pairs
function Get-ObjectMember {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$True)]
        [PSCustomObject]$obj
    )
    $obj | Get-Member -MemberType NoteProperty | ForEach-Object {
        $key = $_.Name
        [PSCustomObject]@{Key = $key; Value = $obj."$key"}
    }
}

有了这个,方法变得更加简单:

$swagger = Get-Content -Path "example_swagger.json" -Encoding UTF8 -Raw | ConvertFrom-Json

$swagger.paths | Get-ObjectMember | ForEach-Object {
    [pscustomobject]@{
        path = $_.Key
        methods = $_.Value | Get-ObjectMember | ForEach-Object Key
    }
}

应用于 https://editor.swagger.io/ 中的默认 Swagger 文件作为示例,这是打印的

path                     methods            
----                     -------            
/pet                     {post, put}        
/pet/findByStatus        get                
/pet/findByTags          get                
/pet/{petId}             {delete, get, post}
/pet/{petId}/uploadImage post               
/store/inventory         get                
/store/order             post               
/store/order/{orderId}   {delete, get}      
/user                    post               
/user/createWithArray    post               
/user/createWithList     post               
/user/login              get                
/user/logout             get                
/user/{username}         {delete, get, put} 

关于json - Powershell 解析 Swagger Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66074896/

相关文章:

json - 播种 Node/MongoDB 应用程序的最佳方法是什么?

c++ - cJSON - 解析 JSON

powershell - PS7.1-如何将管道链接与自定义功能一起使用?

powershell - 将 PowerShell 散列的键/值与 Pester 测试用例一起使用

json - 从 powershell 中的 JSON 对象中删除一个属性

c# - 如何在自定义声明(来自 Auth0)中反序列化 JSON?

java - 我应该如何在 Jackson JSON 中使用数字对象键解析 JSON

java - JSON 加载/获取正确但无法显示

azure - 如何使用 PowerShell 7 获取 Azure 中的任何 Blob 属性