skip to Main Content

having input json like so

[
  {
    "k1": "o1k1",
    "k2": "o1k2",
    "k_opt1": "o1k_xxx"
  },
  {
    "k1": "o2k1",
    "k2": "o2k2",
    "k_opt2": "o2k_yyy"
  }
]

i would like to get array of arrays with object values, so:

[
  [
    "o1k1",
    "o1k2",
    "o1k_xxx"
  ],
  [
    "o2k1",
    "o2k2",
    "o2k_yyy"
  ]
]

tried .[] | to_entries[].value, but it eats up the individual arrays – and produces just:

  "o1k1",
  "o1k2",
  "o1k_xxx",
  "o2k1",
  "o2k2",
  "o2k_yyy"

https://jqplay.org/s/riVFB79OCQS. Any advise?

2

Answers


  1. Just loop through the array and replace objects with Object.value() which creates an array with values of the object.

    EDIT: My bad somehow I got this question and thought it’s about JS. I will still leave this though, might help someone x)

    const data = [
      {
        "k1": "o1k1",
        "k2": "o1k2",
        "k_opt1": "o1k_xxx"
      },
      {
        "k1": "o2k1",
        "k2": "o2k2",
        "k_opt2": "o2k_yyy"
      }
    ]
    
    
    function getKeys(arr) {
      arr.forEach((dataset, i) => {
        arr[i] = Object.values(dataset)
      })
      return arr
    }
    
    console.log(getKeys(data))
    Login or Signup to reply.
  2. Double-nest map(…) or [.[]] (or even .[] |= … on the array, not the object). All of these do what you want:

    jq 'map(map(.))'     # nesting map(…) and map(…)
    jq 'map([.[]])'      # nesting map(…) and [.[]]
    jq '[.[] | [.[]]]'   # nesting [.[]] and [.[]]
    jq '[.[] | map(.)]'  # nesting [.[]] and map(…)
    
    jq '.[] |= map(.)'   # nesting .[] |= … and map(…)
    jq '.[] |= [.[]]'    # nesting .[] |= … and [.[]]
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search