4

linux下如何在命令行下解析处理json文件

 7 months ago
source link: https://bajie.dev/posts/20240119-jq/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Linux下如何在命令行下解析处理json文件

2024-01-19 2 分钟阅读

最近调试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文件了。

curl和jq结合的例子:

curl -s ... | jq .  

如果返回的是一个字符串,不想要字符串的引号,-r即可

curl -s ... | jq '.location.city'  
"Mountain View"

curl -s ... | jq -r '.location.city'  
Mountain View  

如果要计算某个数组的长度,length

curl -s ... | jq '.data | length'  

最后放上Document:

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

jq现在已经到1.7了,有很多新用法,可以计算等等,用法大全:

http://hyperpolyglot.org/json


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK