[英]Replacing the value of JSON based on key value pair with jq
I have a JSON with the following structure我有一个具有以下结构的 JSON
{
"name": "name",
"id": [
"abcdef"
],
"input_dataobjects": [
{
"id": "someid1",
"name": "somename1",
"provider": "someprovider",
"datatype": "somedatatype1"
},
{
"name": "some_name2",
"datatype": "some_datatype2",
"id": "some_id2"
}
]
}
What I am trying to achieve我正在努力实现的目标
in input_dataobjects
if datatype == somedatatype1
then name = sonemewname1
.在input_dataobjects
如果datatype == somedatatype1
那么name = sonemewname1
。
I can use the index of the input_dataobjects since my json always has the same structure.我可以使用 input_dataobjects 的索引,因为我的 json 总是具有相同的结构。 But is there any different way to achieve it by parsing through the input_dataobjects and find the index to replace?但是有没有什么不同的方法可以通过解析 input_dataobjects 并找到要替换的索引来实现它? I am using jq
to do JSON operations.我正在使用jq
进行 JSON 操作。
I tried with using the index like .input_dataobjects[0].name="someting"
because i know the position of the datatype always.我尝试使用像.input_dataobjects[0].name="someting"
这样的索引,因为我总是知道数据类型的位置。
The simplest and perhaps most efficient solution to the problem as stated is: 陈述的最简单,也许最有效的解决方案是:
.input_dataobjects |=
map( if .datatype == "somedatatype1"
then .name = "sonemewname1"
else . end )
here's an alternative solution based on jtc
unix utility: 这是基于jtc
unix实用程序的替代解决方案:
If I understand your question right, you'd like to match datatype== somedatatype1
and if matches, then update the top name
with the name
sibling of datatype
? 如果我理解你的问题吧,你想匹配datatype== somedatatype1
如果匹配,然后更新顶部name
与name
的兄弟姐妹datatype
?
if so, then solution based on jtc
looks like this: 如果是这样,则基于jtc
解决方案如下所示:
bash $ <file.json jtc -w'[name]' -u'[datatype]:<somedatatype1>[-1][name]'
{
"id": [
"abcdef"
],
"input_dataobjects": [
{
"datatype": "somedatatype1",
"id": "someid1",
"name": "somename1",
"provider": "someprovider"
},
{
"datatype": "some_datatype2",
"id": "some_id2",
"name": "some_name2"
}
],
"name": "somename1"
}
bash $
If, you just like to update/alter a sibling name
of the record, then run like this: 如果您只是想更新/更改记录的同级name
,请按以下方式运行:
bash $ <file.json jtc -w'[datatype]:<somedatatype1>[-1][name]' -u'"sonemewname1"'
{
"id": [
"abcdef"
],
"input_dataobjects": [
{
"datatype": "somedatatype1",
"id": "someid1",
"name": "sonemewname1",
"provider": "someprovider"
},
{
"datatype": "some_datatype2",
"id": "some_id2",
"name": "some_name2"
}
],
"name": "name"
}
bash $
here's the jtc
comprehensive user guide 这是jtc
综合用户指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.