Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@joar
Last active March 18, 2024 16:06
Show Gist options
  • Star 83 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save joar/776b7d176196592ed5d8 to your computer and use it in GitHub Desktop.
Save joar/776b7d176196592ed5d8 to your computer and use it in GitHub Desktop.
Add a field to an object with JQ
# Add field
echo '{"hello": "world"}' | jq --arg foo bar '. + {foo: $foo}'
# {
# "hello": "world",
# "foo": "bar"
# }
# Override field value
echo '{"hello": "world"}' | jq --arg foo bar '. + {hello: $foo}'
{
"hello": "bar"
}
# {
# "hello": "bar"
# }
# Concat and add
echo '{"hello": "world"}' | jq --arg foo bar '. + {foo: ("not" + $foo)}'
# {
# "hello": "world",
# "foo": "notbar"
# }
@aborruso
Copy link

aborruso commented Feb 25, 2023

Hi,
I have this input

{
"a":{"fieldA":2,"fieldB":"foo"},
"b":{"fieldA":2,"fieldB":"foo"}
}

And I would like for each key, to add its value inside the related json object

{
"a":{"fieldA":2,"fieldB":"foo","key":"a"},
"b":{"fieldA":2,"fieldB":"foo","key":"b"}
}

If I run this

<input.json jq  '[.|keys[] as $key | .[] + {key: $key}]'

I obtain something similar, but I have the cartesian product

[
  {
    "fieldA": 2,
    "fieldB": "foo",
    "key": "a"
  },
  {
    "fieldA": 2,
    "fieldB": "foo",
    "key": "a"
  },
  {
    "fieldA": 2,
    "fieldB": "foo",
    "key": "b"
  },
  {
    "fieldA": 2,
    "fieldB": "foo",
    "key": "b"
  }
]

How to avoid it?

Thank you

@MaxNanasy
Copy link

@aborruso This seems to work:

jq 'to_entries | map( { (.key) : (.value + { key: .key }) }) | add'

@aborruso
Copy link

aborruso commented Jun 2, 2023

thank you @MaxNanasy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment