Reputation: 37
I need to transform a JSON, which can either have 1 value or 2. So it can be:
{"form":{"textinput1":"aaa"},"params":{"context":""}}
or
{"form":{"textinput1":"aaa"},"params":{"context": "something"}}
And the output I need is this:
{"input": {"text": "aaa"}}
or
{"input": {"text": "aaa"},"context": "something"}}
JQ Transform would be:
{"input": {"text": .form.textinput1}}
or
{"input": {"text": .form.textinput1},"context":.params.context}
But how to merge these two into a condition?
Upvotes: 3
Views: 1802
Reputation: 116740
jq has two basic conditionals: if ... then ... else ... end
and A // B
. In your case, the first suffices:
{"input": {"text": .form.textinput1}}
+ (.params.context | if . == "" then null else {"context":.} end)
If you need to apply some transformation, say f, to .context
if it is not “”, then replace the final .
by f
.
Upvotes: 3
Reputation: 92854
jq solution:
jq '.params.context as $ctx
| {input: {text:.form.textinput1}}
+ (if ($ctx | length) > 0 then {context:$ctx} else {} end)' file.json
.params.context as $ctx
- assign .params.context
value into variable $ctx
if ($ctx | length) > 0
- check if $ctx
is not emptyUpvotes: 1