0

I am very beginner into jq and I want to reshape my JSON file.

I have ve got JSON structured like this:

{
   "a": [1, 2, 3, 4 ...],
   "b": [
      {
         "x": 1000,
         "value": 1
      },
      {
         "x": 1000,
         "value": 2
      },
      {
         "x": 1000,
         "value": 3
      }
      ...
   ]
}

I am wondering how I can achieve result like this with jq:

[
   {
      "value": 1,
      "from": "a",
   },
   {
      "value": 2,
      "from": "a"
   },
   ...
   {
      "value": 1,
      "from": "b"
   },
   {
      "value": 2,
      "from": "b"
   }
   ...
]
2
  • 1
    Are there always only two fields in the root object? Commented Mar 23, 2021 at 11:32
  • Giving an example is nice, but it would be much better if you also described the requirements and showed us what you've tried, which would most likely also give some insight into the requirements. Commented Mar 23, 2021 at 11:55

2 Answers 2

1

Here is a very slightly generic, but hardly robust, solution:

map_values( if type == "array" 
            then map(if type == "object" then .value else . end) 
            else . end)
| [ keys_unsorted[] as $k
    | .[$k][] as $v
    | { value: $v, from: $k } ]
Sign up to request clarification or add additional context in comments.

Comments

0

Create two lists, one from .a and one from .b, and merge them with +. In the first list, create objects with value: set to the original content and add from: "a"; in the second list, remove .x from elements of .b and add the from again.

jq '[.a[] | {value:(.), from: "a"}] + [.b[] | del(.x) + {from: "b"}]

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.