Mcore8x
Mcore8x

Reputation: 143

Formatting an existing json to correct json format in powershell

I've a json file, and there is a comma in the end of JSON object. How to remove the last comma of Item2? Opening this file in the notepad++ having json viewer plugin/Format json removes the commas from Item1, Item2 and last json object.

Does PowerShell support reading this json and format properly like notepad++ does? Found this documentation https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.2

Did not find any options in ConvertTo-Json to format the json given below. And write same json again in correct format.

{
    "Name": "SampleName",
    "Cart": [
        {
            "Item1": "ItemOne",
            
        },
        {
            "Item2": "ItemTwo",
            
        },
    ]
}

Expected json output

{
    "Name": "SampleName",
    "Cart": [
        {
            "Item1": "ItemOne"
        },
        {
            "Item2": "ItemTwo"
        }
    ]
}

Upvotes: 1

Views: 625

Answers (1)

Brice
Brice

Reputation: 814

You can use the third-party module newtonsoft.json

Then the cmdlet ConvertFrom-JsonNewtonsoft will accept this malformatted JSON file. Once converted to an object you can convert it back to a json valid string

$a = @"
{
    "Name": "SampleName",
    "Cart": [
        {
            "Item3": "ItemOne",
            
        },
        {
            "Item2": "ItemTwo",
            
        },
    ]
}
"@
$a | ConvertFrom-JsonNewtonsoft | ConvertTo-JsonNewtonsoft

Upvotes: 2

Related Questions