skip to Main Content

How can I make a key value dictionary using jq?

If I do: cat api_fm.json | jq -r "[ .[].name, .[].status ]"
I receive:

[
  "plugin",
  "c_docker_2",
  "c_docker_5",
  "c_docker_4",
  "c_docker_3",
  "c_docker_1",
  "Started",
  "Started",
  "Started",
  "Started",
  "Started",
  "Started"
]

So, I would like to map the name with the status like this:

[
   "plugin: started"
...
]

2

Answers


  1. Here is one way:

    jq 'map("(.name): (.status)")'
    
    Login or Signup to reply.
  2. Working through the requirements in your comment. Given:

    $ cat api_fm.json
    [
      {"name":"plugin", "status":"Started"},
      {"name":"c_docker_2", "status":"Started"},
      {"name":"c_docker_5", "status":"Started"},
      {"name":"c_docker_4", "status":"Started"},
      {"name":"c_docker_3", "status":"Started"},
      {"name":"c_docker_1", "status":"Started"}
    ]
    

    We can produce tab-separated name-status pairs like

    $ jq -r '.[] | [.name, .status] | @tsv' api_fm.json
    plugin  Started
    c_docker_2  Started
    c_docker_5  Started
    c_docker_4  Started
    c_docker_3  Started
    c_docker_1  Started
    

    Then, to create the bash associative array

    declare -A prod
    
    while IFS=$'t' read -r name status; do
        prod["$name"]=$status
    done < <(
        jq -r '.[] | [.name, .status] | @tsv' api_fm.json
    )
    
    declare -p prod
    
    declare -A prod=([c_docker_2]="Started" [c_docker_3]="Started" [c_docker_1]="Started" [c_docker_4]="Started" [c_docker_5]="Started" [plugin]="Started" )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search