最近调试Elasticsearch比较多,老用curl来查看数据,pretty=on固然是好,可是如果要具体看传回来的json数据,还是不方便,另外如果想在shell里处理json格式,就不知道如何是好了。就被迫改用python了,有没有在shell下调试json的工具呢?
有,就是jq,安装so easy:
wget http://stedolan.github.io/jq/download/linux32/jq (32-bit system) wget http://stedolan.github.io/jq/download/linux64/jq (64-bit system) chmod +x ./jq mv jq /usr/local/bin 给个json样本文件
cat google.json { "name": "Google", "location": { "street": "1600 Amphitheatre Parkway", "city": "Mountain View", "state": "California", "country": "US" }, "employees": [ { "name": "Michael", "division": "Engineering" }, { "name": "Laura", "division": "HR" }, { "name": "Elise", "division": "Marketing" } ] } 看上面,{}括起来的是对象,如果是[]括起来的就是数组了,nodejs要注意这一点,其实json是js的Object的子集。
获取对象:
cat google.json | jq '.name' "Google" 获取嵌套对象:
cat google.json | jq '.location.city' "Mountain View" 获取一个数组的值:
cat google.json | jq '.employees[0].name' "Michael" 获取对象的多个字段:
cat google.json | jq '.location | {street, city}' { "city": "Mountain View", "street": "1600 Amphitheatre Parkway" } 很简单吧,和curl结合起来,就可以在shell进行编程处理json文件了。
...