jq: print key and value for each entry in an object

前端 未结 2 1374
梦如初夏
梦如初夏 2020-11-30 23:31

How do I get jq to take json like this:

{
  \"host1\": { \"ip\": \"10.1.2.3\" },
  \"host2\": { \"ip\": \"10.1.2.2\" },
  \"host3\": { \"ip\         


        
2条回答
  •  北海茫月
    2020-11-30 23:58

    To get the top-level keys as a stream, you can use the built-in function keys[]. So one solution to your particular problem would be:

    jq -r 'keys[] as $k | "\($k), \(.[$k] | .ip)"' 
    

    keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted.

    Another alternative, which produces keys in the original order, is:

    jq -r 'to_entries[] | "\(.key), \(.value | .ip)"'
    

    CSV and TSV output

    The @csv and @tsv filters might also be worth considering here, e.g.

    jq -r 'to_entries[] | [.key, .value.ip] | @tsv'
    

    produces:

    host1   10.1.2.3
    host2   10.1.2.2
    host3   10.1.18.1
    

    Embedded objects

    If the keys of interest are embedded as in the following example, the jq filter would have to be modified along the lines shown.

    Input:

    {
      "myhosts": {
        "host1": { "ip": "10.1.2.3" },
        "host2": { "ip": "10.1.2.2" },
        "host3": { "ip": "10.1.18.1" }
      }
    }
    

    Modification:

    jq -r '.myhosts | keys[] as $k | "\($k), \(.[$k] | .ip)"'
    

提交回复
热议问题