Search code examples
arraysjsonpowershellconvertto-json

Convert JSON array object to String in Powershell


I am working with a JSON like that looks like this:

[
    {
        "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]. 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.


Solution

  • ConvertFrom-Json may work for you. 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 = @"
    [
        {
            "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.