Reputation: 55
now I have following problem.
there is such input json
{
“inn” : “qwerty”,
“cuid” : “1234”,
“type” : "legal",
“reqId” : “asdfg”
}
It should be transformed into
{
“inn” : “qwerty”,
“reqId” : “asdfg”
}
or into
{
“cuid” : “1234”,
“reqId” : “asdfg”
}
it depends on a value of "type" field. How can I do that with JQ?
My attempts were failed, it all was about trying such way
.inn as $inn | .cuid as $cuid | {if .type == "person" then $inn else $cuid end}
but it gave such result
jq: error: syntax error, unexpected FIELD, expecting ':' (Unix shell quoting issues?) at , line 1: .inn as $inn | .cuid as $cuid | {if .type == "person" then $inn else $cuid end}
jq: 1 compile error exit status 3
Upvotes: 0
Views: 103
Reputation: 2200
You can solve your problem easily with one if then else end
expression:
jq 'if .type == "person"
then {inn, reqId}
else {cuid, reqId}
end' <<< '{ "inn" : "qwerty", "cuid" : "1234", "type" : "legal", "reqId" : "asdfg" }'
# result
# {
# "cuid": "1234",
# "reqId": "asdfg"
# }
jq 'if .type == "person"
then {inn, reqId}
else {cuid, reqId}
end' <<< '{ "inn" : "qwerty", "cuid" : "1234", "type" : "person", "reqId" : "asdfg" }'
# result
# {
# "inn": "qwerty",
# "reqId": "asdfg"
# }
Upvotes: 0
Reputation: 43904
To get the following filter where:
.type == "person"
--> We use keys: inn
and reqId
.type != "person"
--> We use keys: cuid
and reqId
We can use:
if .type == "person" then { inn } else { cuid } end + { reqId }
The differences I've made:
Added the last part: + { reqId }
. Here we add the reqId
to the object created by the if
statement.
I've removed the .inn as $inn
part this we can just use the key for this.
Upvotes: 1