简体   繁体   English

将 JSON 数组 object 转换为 Powershell 中的字符串

[英]Convert JSON array object to String in Powershell

I am working with a JSON like that looks like this:我正在使用 JSON ,如下所示:

[
    {
        "Ack":  "no",
        "Rule":  "dont",
        "Tags":  [
                     "server"
                 ],
        "Type":  "blue"
    },

    {
        "Ack":  "no1",
        "Rule":  "knock",
        "Tags":  [
                     "yellow",
                     "green"
                 ],
        "Type":  "multiplecolour"
    }

]

I need to convert the Tags array into a comma-separated string [and replace the array with the converted string in the JSON file].我需要将 Tags 数组转换为逗号分隔的字符串 [并用 JSON 文件中的转换字符串替换数组]。 I have tried converting from JSON, but I am struggling to convert the array into string in a clean way, still learning PS so please bear with me.我已经尝试从 JSON 转换,但我正在努力以干净的方式将数组转换为字符串,仍在学习 PS,所以请多多包涵。

ConvertFrom-Json may work for you. ConvertFrom-Json可能对您有用。 Here's an example of converting your JSON string to an array of PowerShell objects, then joining the tags for each object with a comma delimiter:这是将 JSON 字符串转换为 PowerShell 对象数组的示例,然后使用逗号分隔符连接每个 object 的标签:

$json = @"
[
    {
        "Ack":  "no",
        "Rule":  "dont",
        "Tags":  [
                     "server"
                 ],
        "Type":  "blue"
    },
    {
        "Ack":  "no1",
        "Rule":  "knock",
        "Tags":  [
                     "yellow",
                     "green"
                 ],
        "Type":  "multiplecolour"
    }
]
"@

(ConvertFrom-Json -InputObject $json) `
    | ForEach-Object { $_.Tags = ($_.Tags -join ","); $_ } `
    | ConvertTo-Json `
    | Out-File -FilePath new.json

EDIT: Note (as @mklement0 points out), the parentheses around ConvertFrom-Json are required to force the enumeration of the results as an array of objects through the pipeline.编辑:注意(正如@mklement0 指出的那样), ConvertFrom-Json周围的括号需要强制将结果枚举为通过管道的对象数组

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

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