0

I have the following JSON;

[
  {
    "id": 1,
    "start": "2022-06-20",
    "result": 24
  },
  {
    "id": 2,
    "start": "2022-06-21",
    "result": 56
  },
  {
    "id": 3,
    "start": "2022-06-21",
    "result": 78
  }
]

I'm wanting to add 2 new values to each array above using JQ, dimension and date, but date needs to be a copy of the existing key value start. The expected output is as below;

[
  {
    "id": 1,
    "start": "2022-06-20",
    "result": 24,
    "date": "2022-06-20",
    "dimension": "new"
  },
  {
    "id": 2,
    "start": "2022-06-21",
    "result": 56,
    "date": "2022-06-21",
    "dimension": "new"
  },
  {
    "id": 3,
    "start": "2022-06-21",
    "result": 78,
    "date": "2022-06-21",
    "dimension": "new"
  }
]

The jq I have at present can add the new key dimension, but I can't figure out how to copy start -> date

jq '.[] += {"dimension": "new"}' input.json

Thanks for any help

2 Answers 2

4

Just create the new key / value pairs.

jq 'map(.date = .start | .dimension = "new")' input.json
Sign up to request clarification or add additional context in comments.

1 Comment

@Inian, sh makes more sense than none.
1

You might have tried the following:

.[] += { date: .start, dimension: "new" }    // WRONG

But it's not quite right since . is the array, not the element of the array. You can use |= as a topicalizer.

.[] |= ( . += { date: .start, dimension: "new" } )

But I'd use map instead.

map( . += { date: .start, dimension: "new" } )

Alternatively,

. += { date: .start, dimension: "new" }

can also also be achieved using

.date = .start | .dimension: "new"

So you could use

.[] |= ( .date = .start | .dimension: "new" )

or

map( .date = .start | .dimension = "new" )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.