skip to Main Content

I have a question.
Let’s assume I had a json doc like this:

{
  "counts": [
    17,
    1014,
    22,
    9,
    11
  ],
  "values": [
    "5",
    "10",
    "15",
    "20",
    "25"
  ]
}

and I wanted to get a result like this:

{
    "5":17,
    "10":1014,
    "15":22,
    "20":9,
    "25":11
}

basically the array elements assigned as key value pairs one after the other. How can I achieve that?

I tried jq with_entries(.values = .counts) and with_entries(.values[] = .counts[]) but it didn’t work.

2

Answers


  1. I’d use transpose with reduce:

    [ .counts, .values ] | transpose | reduce .[] as $t ({}; .[$t[1]] = $t[0])
    

    Output:

    {
      "5": 17,
      "10": 1014,
      "15": 22,
      "20": 9,
      "25": 11
    }
    

    Online Demo

    Login or Signup to reply.
  2. Here are two transpose-free solutions:

    [(.counts | keys[]) as $i | {(.values[$i]): .counts[$i]}] | add
    

    Demo

    . as {$values} | .counts | with_entries(.key |= $values[.])
    

    Demo

    Output:

    {
      "5": 17,
      "10": 1014,
      "15": 22,
      "20": 9,
      "25": 11
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search