【问题标题】:JSON formatting, either from file or variableJSON 格式,来自文件或变量
【发布时间】:2018-04-28 08:49:45
【问题描述】:

我有一个 PS 脚本,它在变量 ant 中获取 JSON,然后将其保存在文件中。

不幸的是,它在一个字符串中获取值,如下所示:

{   "persistentdataapi": "https://somevalue.azurewebsites.net/",   "collectioncountapi": "https://anothervalue.azurewebsites.net/",   "eventserviceapi": "https://thirdvalue.azurewebsites.net/",   "securityserviceapi": "https://fourthvalue.azurewebsites.net/" }

有什么办法,通过一些(最好是PS)JSON格式处理这个值,得到这个:

{
"persistentdataapi": "https://somevalue.azurewebsites.net/",
"collectioncountapi": "https://anothervalue.azurewebsites.net/",
"eventserviceapi": "https://thirdvalue.azurewebsites.net/",
"securityserviceapi": "https://fourthvalue.azurewebsites.net/",
}

在 Jenkins 中获取价值的代码:

Import-Module "C:\Program Files\WindowsPowerShell\Modules\Octopus-Cmdlets\0.4.4\Octopus-Cmdlets.psd1"

connect-octoserver http://internal-Octopus.azure.com:8082 API-123456789012345678
$raw = (Get-OctoVariable var.Portal.Web DataAPIJson | Where-Object { $_.Environment -eq "QA" } )

$raw.Value | Out-File "$env:WORKSPACE\portal\var.Portal.Web\dataapi.json"

【问题讨论】:

    标签: json powershell pretty-print


    【解决方案1】:

    Powershell 默认会漂亮打印它生成的任何 JSON。

    所以进行漂亮打印的正确方法是将 JSON 字符串解析为对象,然后立即将其转换回 JSON 字符串。

    $json = '{   "persistentdataapi": "https://somevalue.azurewebsites.net/",   "collectioncountapi": "https://anothervalue.azurewebsites.net/",   "eventserviceapi": "https://thirdvalue.azurewebsites.net/",   "securityserviceapi": "https://fourthvalue.azurewebsites.net/" }'
    
    $json | ConvertFrom-Json | ConvertTo-Json
    

    产生

    {
        "persistentdataapi":  "https://somevalue.azurewebsites.net/",
        "collectioncountapi":  "https://anothervalue.azurewebsites.net/",
        "eventserviceapi":  "https://thirdvalue.azurewebsites.net/",
        "securityserviceapi":  "https://fourthvalue.azurewebsites.net/"
    }
    

    或者在你的情况下

    $file = "$env:WORKSPACE\portal\var.Portal.Web\dataapi.json"
    $raw.Value | ConvertFrom-Json | ConvertTo-Json | Out-File $file -Encoding UTF8
    

    作为一个副作用,这也确保了文件中的 JSON 是有效的,否则ConvertFrom-Json 会抛出一个错误。

    始终在读写 JSON 文件时明确指定 UTF8 编码。

    $data = Get-Content $file -Encoding UTF8 | ConvertFrom-Json
    
    $data | ConvertTo-Json | Set-Content $file -Encoding UTF8
    

    原因是

    • 按照广泛接受的约定,JSON 文件应该是 UTF8。
    • 除非另有说明,Get-ContentSet-Content 将使用系统的默认编码来读取/写入文本文件。
    • 系统默认很少使用 UTF-8,大多数情况下它将是像 Windows-1252 这样的传统单字节编码。
    • 这会产生以下风险
      • 在读取 JSON 文件时修改 Unicode 字符,这在 JSON 中是合法的。
      • 创建非 UTF-8 的 JSON 文件,使其难以被其他人使用。

    事实上,在处理文本文件时,总是明确指定编码,不仅仅是在 JSON 的情况下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2012-03-19
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多