Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

How do I get jq to take json like this:

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

and generate this output:

host1, 10.1.2.3
host2, 10.1.2.2
host3, 10.1.18.1

I'm not interested in the formatting, I just can't figure out how to access the key name and value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)"'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...