gpt4 book ai didi

json - 如何在jq walk中引用父对象?

转载 作者:行者123 更新时间:2023-12-03 08:09:10 25 4
gpt4 key购买 nike

我想根据步行添加一些 json。我拥有的 json 的一个简单示例如下:

{
"valueSource": "memory",
"dataType": "Boolean",
"alarms": [
{
"setpointA": 1.0,
"name": "Alarm",
"priority": "Diagnostic",
"ackMode": "Auto",
}
],
"name": "Test Alarm",
"value": false,
"tagType": "AtomicTag"
}

我想向“alarms”键数组中的每个对象添加以下键:

{
"bindType": "Tag",
"value": "[.]<parent.name>.Name"
}

哪里<parent.name>在此示例中是“测试警报”,它是警报数组项的父项的“名称”键。

到目前为止,我已经得到了这个 jq 过滤器,它添加了对象,但是 value键值错误(它获取的是警报数组项的名称而不是其父项的名称):

walk( if type == "object" and .setpointA then .label = {"bindType":"Tag", "value": "[.]\(.name).Name"} else . end)

基本上我想要这个:

{
"valueSource": "memory",
"dataType": "Boolean",
"alarms": [
{
"setpointA": 1.0,
"name": "Alarm",
"priority": "Diagnostic",
"ackMode": "Auto",
"label": {
"bindType": "Tag",
"value": "[.]Test Alarm.Name"
}
}
],
"name": "Test Alarm",
"value": false,
"tagType": "AtomicTag"
}

下面是我的 jqplay。它在 JSON 部分中有最终结果,其中结果应该与此匹配,但目前不匹配。 https://jqplay.org/s/-qHFIWolrD

后续问题:我该如何添加这个displayPath key 也可以吗? enter image description here

最佳答案

您不能引用父级,您必须事先将引用保存在变量中,并在有权访问该变量的情况下下降。

.tags[] |= (
.name as $name
| # rest of your code using $name
walk(
if type == "object" and .setpointA
then .label = {"bindType":"Tag", "value": "[.]\($name).Name"}
else . end
)
)

Demo

当您碰巧知道这些对象位于 .alarms 数组中时,您也可以迭代这些项目,选择 仅那些匹配条件的项目,然后为他们的 .label 分配您想要的任何内容(包括 $name)

.tags[] |= (
.name as $name
| (.alarms[] | select(has("setpointA"))).label = {
bindType: "Tag", value: "[.]\($name).Name"
}
)

Demo


编辑回复OP的后续问题

I actually don't care about the setpointA key, I just want to add the label key (as well as another displayPath key) to each item in all alarms arrays.

.tags[] |= (.name as $name | .alarms[] += (
{bindType: "Tag", value: "[.]\($name)."} | {
label: (.value += "Name"),
displayPath: (.value += "Documentation")
}
))

Demo

关于json - 如何在jq walk中引用父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71308155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com