ikegami
ikegami

Reputation: 385789

Using JQ to copy one field of an object into another

In my JSON are some objects with a Description property. How do I copy this value over to the GMNotes property of the same object using JQ?

In other words, how does one go from

{
   "ObjectStates": [
      {
         "Description": "",
         "GMNotes": ""
      },
      {
         "Description": "foo",
         "GMNotes": ""
      }
   ]
}

to

{
   "ObjectStates": [
      {
         "Description": "",
         "GMNotes": ""
      },
      {
         "Description": "foo",
         "GMNotes": "foo"
      }
   ]
}

.ObjectStates[] | .GMNotes = .Description only returns the modified objects, as shown in the sandbox.

(I could easily do this in Perl. The point is using jq.)

Upvotes: 2

Views: 1979

Answers (1)

hek2mgl
hek2mgl

Reputation: 157967

You can use map() in combination with the update assignment operator |=:

jq '(.ObjectStates)|=map(.GMNotes=.Description)' file.json

https://jqplay.org/s/vFV_H4brlH

PS: instead of using map you could also just use the following command, the key is using |=.

jq '.ObjectStates[]|=(.GMNotes=.Description)' file.json

thanks chepner!

https://jqplay.org/s/NCGezXPjLE

Upvotes: 8

Related Questions