1

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"
        }
    ]
}
4
  • No, it is simply an invalid Json string (only peeking/poking directly into the string might correct this, which I would discourage you to do). You should investigate how you created the sting/file as no respected Json serializer should allow this to happen. Commented Sep 7, 2022 at 11:43
  • This json is coming from buggy script written in PowerShell. Will try to fix it in original file writer. Commented Sep 7, 2022 at 11:50
  • 1
    If you can post that script, we might be able to help you Commented Sep 7, 2022 at 11:55
  • Thanks @Theo Fixed in the script however I got answer. Commented Sep 12, 2022 at 18:00

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.