1

I'm trying to create a single json output based on a nested Json:

{
    "Id" : "1",
    "items" : [
        {"item_name" : "shirt","value" : 10},
        {"item_name" : "dress","value" : 20},
        {"item_name" : "ice cream","value" : 30}
    ] 
}

My expected output would be:

[
  {
    "id": "1",
    "item_name": "shirt",
    "value": 10,
    "index_position": 0
  },
  {
    "id": "1",
    "item_name": "dress",
    "value": 20,
    "index_position": 1
  },
  {
    "id": "1",
    "item_name": "ice cream",
    "value": 30,
    "index_position": 2
  }
]

The only output that I was able to fetch is on this snippet:

https://jqplay.org/s/G6mYAI47LE

What would be the best way to iterate over an inner array and at the same time fetch the outer object data?

1 Answer 1

1

Q.E.D. as follows:

.Id as $Id
| .items
| [ range(0; length) as $index_position
   | {$Id} + .[$index_position] + {$index_position} ]

The key to brevity (or at least DRY-ness) here is that the jq expression {$x} expands to {"x": $x}.

Sign up to request clarification or add additional context in comments.

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.