jq

最後更新: 2017-12-20

介紹

jq is sed for JSON

Command-line JSON processor

jq is written in portable C, and it has zero runtime dependencies.

HomePage: https://stedolan.github.io/jq/

目錄


Install

 

apt-get install jq

dnf install jq

 


Opts

 

  • --raw-output / -r            
    if the filter´s result is a string then it will be written directly to stdout
    rather than being formatted as a JSON string with quotes.
  •  

 

 


Usage

 

Pretty-print

# The simplest filter is "." which echoes its input, but pretty-printed:

echo '{"hello":{ "greetings":"to you"}}' | jq .

Or

jq . file.json

Notes: keep colors when piping "jq" output to "less"

By default, jq outputs colored JSON if writing to a terminal.

You can force it to produce color even if writing to a pipe or a file using -C

curl -s http://localhost:9200/_nodes | jq -C .nodes | less -r

Field

single field

# ".field" which pulls "field" out of each record:

echo '{"hello":{ "greetings":"to you"}}' | jq .hello

nested hashes: .field1.field2

echo '{"hello":{ "greetings":"to you"}}' | jq .hello.greetings

兩個 Field: ","

[1]

jq .foo.bar

[2]

jq '.foo, .bar'

{"foo": 42, "bar": "something else", "baz": true} => 42, "something else"

Array

Array Index

.[N]

start with 0

Slice

echo '["a","b","c","d","e"]' | jq '.[2:4]'

Go “into” the array

.[] = Array/Object Value Iterator

有 go “into” Array/Object 的作用

.[]?

Like .[], but no errors will be output if . is not an array or object.

 


Example

 

#1 找出 array 內每個 item 的 feild

ip-ranges.json

[
  {
    "ip_prefix": "3.2.34.0/26",
    "region": "af-south-1",
    "service": "AMAZON",
    "network_border_group": "af-south-1"
  },
  {
    "ip_prefix": "3.5.140.0/22",
    "region": "ap-northeast-2",
    "service": "AMAZON",
    "network_border_group": "ap-northeast-2"
  },
  ...
]

# "| .text" filter by text

cat ip-ranges.json | jq .prefixes | jq ".[] | .ip_prefix"

Notes

jq ".[] | .ip_prefix" 可以簡寫成  jq ".[].ip_prefix"

#2 在 elasticsearch 找出每個 node

curl -s http://localhost:9200/_nodes/ | jq '.nodes | keys'

# node 的基本資料

curl -s http://localhost:9200/_nodes/ | jq '.nodes | .[] | .name, .ip, .version, .roles, .attributes'