如何使用PowerShell将JSON数组解析成单独的文件?

i5desfxk  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(170)

PowerShell脚本将提供以下输入文件:

{
    "array": [
        {
            "field1": "value1",
            "field2": "value2", 
            "field3": "value3",
            "field4": "value4",
            "field5": "value5"
        },
        {
            "field1": "value6",
            "field2": "value7", 
            "field3": "value8",
            "field4": "value9",
            "field5": "value10"
        }
    ]
}

我需要将其分解到单独的json文件中。文件1名称:文件1.json

{
   "field1": "value1",
   "field2": "value2", 
   "field3": "value3",
   "field4": "value4",
   "field5": "value5"
}

文件2名称:文件2.json

{
   "field1": "value6",
   "field2": "value7", 
   "field3": "value8",
   "field4": "value9",
   "field5": "value10"
}
w9apscun

w9apscun1#

使用ConvertFrom-Json解析输入文件,然后使用ConvertTo-Json导出数组中的每个单独对象


# import and parse input

$data = Get-Content .\path\to\input.json |ConvertFrom-Json

$count = 0
foreach($item in $data.array){
  $count++
  # export each array item as json
  $item |ConvertTo-Json |Set-Content "file${count}.json"
}

相关问题