Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 605
mr i.o Avatar asked Nov 21 '25 02:11

mr i.o


1 Answers

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.

like image 119
Glenn Avatar answered Nov 23 '25 06:11

Glenn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!