如何使用Powershell解析JSON文件的条件

问题描述 投票:0回答:1

我想使用powershell和json文件。我有一个从Powershell上的Invoke-RestMethod生成的JSON文件。

输出json文件如下所示:

[
    {
        "_id": "ID1",
        "isTemplate": true,
        "origin": "SPO_Promoteur_DEV",
        "tenant": "spo",
        "reference": "HbiuOzq1u",
        "date": "2019-02-04T16:01:35.230Z",
        "data":
        {
            "tasks":
            {
                "rows": [
                    {
                        "parentId": "root",
                        "entities": [
                            "Something there"
                        ],
                        "Name": "A name there"
                    },
                    {
                        "parentId": "Z9zgsHzFad",
                        "entities": [
                            "urn:CodeEtape:DONGEN:CodeAction:TEST1"
                        ],
                        "Duration": 0,
                        "index": 0,
                        "Id": "wWotapvig"
                    }
                ]
            }
        }
    },
    {
        "_id": "ID12",
        "isTemplate": true,
        "origin": "SPO_Promoteur_DEV",
        "tenant": "spo",
        "reference": "Hbkjh548u",
        "date": "2019-02-04T16:01:35.230Z",
        "data":
        {
            "tasks":
            {
                "rows": [
                    {
                        "parentId": "root",
                        "entities": [
                            "Something else there"
                        ],
                        "Name": "An other name there"
                    },
                    {
                        "parentId": "Z9zgszffzfHzFad",
                        "entities": [
                            "urn:CodeEtape:DONGEN:CodeAction:TEST1"
                        ],
                        "Duration": 0,
                        "index": 0,
                        "Id": "wWotapvig"
                    }
                ]
            }
        }
    }
]

我想分开这个json文件。我如何生成名为reference.json的json文件(在json主文件中给出引用)并将isTemplate设为true?

所以我将得到X文件,每个文件都有他们的引用作为名称,并且每个文件都有IsTemplate参数为TRUE。

谢谢你的帮助

json powershell
1个回答
2
投票

如果我正确理解了这个问题,你可以在json文件中读取,该文件包含一个项目数组,并将每个项目保存为单独的新json文件,如下所示。

每个项目都有一个reference_XYZ.json的文件名,其中'XYZ'将是'_id'值。

$inputFile  = 'FULL PATH TO YOUR INPUT JSON FILE'
$outputPath = Split-Path $inputFile -Parent
$json       = Get-Content -Raw -Path $inputFile | ConvertFrom-Json

foreach ($item in $json) {
    $fileName = Join-Path -Path $outputPath -ChildPath ('reference_{0}.json' -f $item._id)
    $item | ConvertTo-Json -Depth 10 | Out-File $fileName
}

我不太清楚你的意思是什么,并且他们每个人都有IsTemplate参数为TRUE,因为这两个项目都将该属性设置为True ..

如果您只想保存具有此"isTemplate": true的项目而忽略其他错误的项目,只需将Where-Object子句添加到foreach循环中,如下所示:

foreach ($item in ($json | Where-Object { $_.isTemplate -eq $true})) {
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.