简体   繁体   English

格式化现有的 json 以更正 powershell 中的 json 格式

[英]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.我有一个 json 文件,JSON object 末尾有一个逗号。 How to remove the last comma of Item2?如何删除Item2的最后一个逗号? Opening this file in the notepad++ having json viewer plugin/Format json removes the commas from Item1, Item2 and last json object.在具有 json 查看器插件/格式 json 的记事本 ++ 中打开此文件会删除 Item1、Item2 和最后一个 json2668CFDE63931AC4BEB68 中的逗号

Does PowerShell support reading this json and format properly like notepad++ does? PowerShell 是否支持读取此 json 并像 notepad++ 那样正确格式化? Found this documentation https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.2找到此文档https://docs.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.在 ConvertTo-Json 中没有找到任何选项来格式化下面给出的 json。 And write same json again in correct format.并以正确的格式再次写入相同的 json。

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

Expected json output预期 json output

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

You can use the third-party module newtonsoft.json可以使用第三方模块newtonsoft.json

Then the cmdlet ConvertFrom-JsonNewtonsoft will accept this malformatted JSON file.然后 cmdlet ConvertFrom-JsonNewtonsoft将接受此格式错误的JSON文件。 Once converted to an object you can convert it back to a json valid string转换为 object 后,您可以将其转换回 json 有效字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM