我正在尝试根据一些条件更新 JSON 文件的某些属性:
ismydata
属性必须是true
.deprecatedVersion
的值必须为空字符串。此处显示了我尝试更新的示例 JSON:
{
"name": "account",
"description": "Some description",
"attributes": {
"accountNameCode": {
"description": "Name of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
},
"accountNameDescription": {
"description": "Description of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
},
"anotherDescription": {
"description": "Some other thing.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
}
}
}
目前,我有以下脚本几乎需要什么,但是它会为找到的每个匹配项复制 JSON 主体:
(.attributes
| with_entries( select(.key|contains("Description")))
| keys[] as $k | .[$k]
| select(.ismydata==true) and select(.deprecatedVersion=="") | $k) as $matchKey
| .attributes[$matchKey].description as $description
| .attributes[$matchKey].deprecatedVersion |= "Y"
| .attributes[$matchKey].description |= "Deprecated- this has been replaced by... " + $description
这导致以下 -
{
"name": "account",
"description": "Some description",
"attributes": {
"accountNameCode": {
"description": "Name of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
},
"accountNameDescription": {
"description": "Deprecated- This property has been replaced by the enumerationDataType.description field. Description of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": "Y"
},
"anotherDescription": {
"description": "Some other thing.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
}
}
}
{
"name": "account",
"description": "Some description",
"attributes": {
"accountNameCode": {
"description": "Name of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
},
"accountNameDescription": {
"description": "Description of the account type.",
"type": "string",
"ismydata": true,
"deprecatedVersion": ""
},
"anotherDescription": {
"description": "Deprecated- This property has been replaced by the enumerationDataType.description field. Some other thing.",
"type": "string",
"ismydata": true,
"deprecatedVersion": "Y"
}
}
}
根据问题描述和示例代码,看来您基本上是在尝试更新 .attributes;最简单的方法可能是使用以下形式:
.attributes |= ...
事实上,以下似乎是一个解决方案:
.attributes |=
with_entries(
if (.key|contains("Description"))
and .value.ismydata == true
and .value.deprecatedVersion == ""
then .value |=
((.deprecatedVersion = "Y")
| .description |= "Deprecated- this has been replaced by ...\(.)")
else .
end)
(此解决方案与@Newpaw 建议的解决方案非常相似,但随后被删除。)