3

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Nice, though it's worth pointing out that (...) is required, because it forces enumeration of the array that ConvertFrom-Json sends as a whole through the pipeline.
@mri.o: Please state all requirements up front in the future - it is not clear from your question as currently stated. Perhaps Glenn is willing to update his answer, but the short of it is that you must use $_.Tags = $_.Tags -join "," instead, and pipe to ConvertTo-Json.
$jsonParameters = (ConvertFrom-Json -InputObject $content) $jsonParameters | ForEach-Object { $_.Tags -join "," } | ConvertTo-Json | out-file new.json - this is how I piped it, the content of new.json is only the tag strings. @Glenn. It doesn't create it properly.
@mri.o So, your intent is to reproduce the JSON with the only difference being that "Tags" is no longer an array, but a string property, which contains one or more comma-delimited values? For example, it becomes this for the second array element? "Tags": "yellow,green"
Learnt something new today, thanks @Glenn, latest update works!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.