[英]Need to iterate through json and add new json entries using python
[英]Iterate through a text file and add entries to the JSON using powershell
我有一个包含以下动态生成的数据的文本文件,因此 repo.txt 的内容不断变化
repo.txt -> Content as below
repo1
repo2
repo_3
和一个 JSON 文件
template.json -> Content as below
{
"name": "new-report-test-1",
"resources": {
"repositories": [
{
"name": "repoa"
},
{
"name": "repo_b"
}
]
},
"filters": {
"severities": [
"High"
]
}
}
现在我想从 repo.txt 文件中读取 repo 列表并将 template.json 更新到下面
{
"name": "new-report-test-1",
"resources": {
"repositories": [
{
"name": "repoa"
},
{
"name": "repo_b"
},
{
"name": "repo1"
},
{
"name": "repo2"
},
{
"name": "repo_3"
}
]
},
"filters": {
"severities": [
"High",
"Medium",
"Critical"
]
}
}
我有这个 bash 脚本可以完成这项工作,但我不确定如何将它翻译成 PoweShell。 任何意见将不胜感激
cat ./tmpgen_reponames.txt | while read repoEntry do echo " Repository: $repoEntry" cat <<< $(jq --arg REPOID "$repoEntry" '[ .[] , {"name":$REPOID} ]' tmpgen_repoarray.json) > tmpgen_repoarray.json done
您可以在 PowerShell 中使用ConvertFrom-Json
将您的 Json 转换为对象,然后按照面向对象的方法将新的自定义对象添加到.resources.repositories
属性并将新值Medium
和Critical
添加到.filters.severities
属性您的 Json,最后,使用ConvertTo-Json
将其转换回 Json 字符串:
$json = Get-Content path\to\template.json -Raw | ConvertFrom-Json
$json.resources.repositories = @(
$json.resources.repositories
(Get-Content path\to\repo.txt).Trim() | ForEach-Object {
[pscustomobject]@{ Name = $_ }
}
)
$json.filters.severities = @(
$json.filters.severities
'Medium'
'Critical'
)
$json | ConvertTo-Json -Depth 99 | Set-Content path\to\newJson.Json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.