![](/img/trans.png)
[英]How to extract values from a JSON file using PowerShell under certain conditions?
[英]How to parse JSON File using Powershell, with conditions
我想使用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文件,該文件包含一個項目數組,並將每個項目另存為單獨的新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
項目,而忽略其他為false的項目,則只需將一個Where-Object
子句添加到foreach
循環中,如下所示:
foreach ($item in ($json | Where-Object { $_.isTemplate -eq $true})) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.