Ferramenta de saída de formatação JSON, aprendizado de uso de jq

jqé uma ferramenta de linha de comando para manipular dados JSON. Ele pode ajudá-lo a formatar, consultar, filtrar e editar dados JSON complexos para melhor processamento e análise de dados.

1. Instalação

1.1. instalação do pacote yum

$ yum install jq
No match for argument: jq
Error: Unable to find a match: jq

O pacote não foi encontrado na configuração da máquina yum source.

1.2. Instale usando o pacote rpm

Instalação do pacote de download da comunidade:

Endereços de pacotes da comunidade Linux comumente usados:https://centos.pkgs.org/

$ wget http://www6.atomicorp.com/channels/atomic/centos/7/x86_64/RPMS/jq-1.6-2.el7.x86_64.rpm

$ rpm -ivh jq-1.6-2.el7.x86_64.rpm 
warning: jq-1.6-2.el7.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 4520afa9: NOKEY
error: Failed dependencies:
	libonig.so.5()(64bit) is needed by jq-1.6-2.el7.x86_64

Erro de instalação, falta de dependências, dependências de instalação ainda falham:

$ yum localinstall oniguruma-devel-6.8.2-2.el7.x86_64.rpm 
Last metadata expiration check: 0:07:38 ago on Tue 27 Jun 2023 10:15:12 AM CST.
Error: 
 Problem: conflicting requests
  - nothing provides libonig.so.5()(64bit) needed by oniguruma-devel-6.8.2-2.el7.x86_64

Instale usando a ferramenta de liberação atômica:

$ wget http://www6.atomicorp.com/channels/atomic/centos/7/x86_64/RPMS/atomic-release-1.0-23.el7.art.noarch.rpm

$ rpm -Uvh atomic-release-1.0-23.el7.art.noarch.rpm 
warning: atomic-release-1.0-23.el7.art.noarch.rpm: Header V4 RSA/SHA256 Signature, key ID 4520afa9: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:atomic-release-1.0-23.el7.art    ################################# [100%]

# 安装atomic-release实际上是在本地新建atomic.repo yum源文件
$ ll /etc/yum.repos.d/ | grep atomic
-rw-r--r--  1 root root  743 Jan  5  2022 atomic.repo

$ yum install jq
CentOS / Red Hat Enterprise Linux 7 - atomic                                                                                                 80 kB/s | 205 kB     00:02    
Last metadata expiration check: 0:00:00 ago on Tue 27 Jun 2023 10:28:38 AM CST.
Dependencies resolved.
============================================================================================================================================================================
 Package                                   Arch                                   Version                                      Repository                              Size
============================================================================================================================================================================
Installing:
 jq                                        x86_64                                 1.6-2.el7                                    atomic                                 167 k
Installing dependencies:
 oniguruma                                 x86_64                                 6.8.2-1.el7                                  atomic                                 181 k

Transaction Summary
============================================================================================================================================================================
Install  2 Packages

Total download size: 348 k
Installed size: 1.0 M
Is this ok [y/N]: y
Downloading Packages:
(1/2): oniguruma-6.8.2-1.el7.x86_64.rpm                                                                                                      90 kB/s | 181 kB     00:02    
(2/2): jq-1.6-2.el7.x86_64.rpm                                                                                                               83 kB/s | 167 kB     00:02    
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                       102 kB/s | 348 kB     00:03     
warning: /var/cache/dnf/atomic-e5cca8bbd0dce12d/packages/jq-1.6-2.el7.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 4520afa9: NOKEY
Importing GPG key 0x4520AFA9:
 Userid     : "Atomicorp (Atomicorp Official Signing Key) <[email protected]>"
 Fingerprint: 1818 66DF 9DAC A40E 5B42 9B08 FFBD 5D0A 4520 AFA9
 From       : https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt
Is this ok [y/N]: y
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                    1/1 
  Installing       : oniguruma-6.8.2-1.el7.x86_64                                                                                                                       1/2 
  Running scriptlet: oniguruma-6.8.2-1.el7.x86_64                                                                                                                       1/2 
  Installing       : jq-1.6-2.el7.x86_64                                                                                                                                2/2 
  Running scriptlet: jq-1.6-2.el7.x86_64                                                                                                                                2/2 
  Verifying        : jq-1.6-2.el7.x86_64                                                                                                                                1/2 
  Verifying        : oniguruma-6.8.2-1.el7.x86_64                                                                                                                       2/2 
New leaves:
  jq.x86_64

Installed:
  jq.x86_64 1.6-2.el7                                                              oniguruma.x86_64 6.8.2-1.el7                                                             

Complete!

2. jqAplicação

2.1. Formatar dados JSON

Use jq para formatar dados JSON complexos em um formato mais legível.
Por exemplo, {"foo": 0}depois de usar jq para formatar, ele é exibido como:

$ echo '{"foo": 0}' | jq
{
    
    
  "foo": 0
}

Operação em arquivos:

$ cat test.json 
{
    
    "gender":"man","name":"zhangsan","age":"10","score":{
    
    "math":"85","English":"86","Chinese":"87"}}
$ jq . test.json 
{
    
    
  "gender": "man",
  "name": "zhangsan",
  "age": "10",
  "score": {
    
    
    "math": "85",
    "English": "86",
    "Chinese": "87"
  }
}

# 也可以
$ cat test.json | jq 
{
    
    
  "gender": "man",
  "name": "zhangsan",
  "age": "10",
  "score": {
    
    
    "math": "85",
    "English": "86",
    "Chinese": "87"
  }
}

2.2. Consultar dados JSON

Use jq para consultar um determinado campo ou valor em dados JSON.

$ cat test.json | jq '.age'
"10"

# 查看math
$ cat test.json | jq '.score.math'
"85"

ou use:

$ jq '.age' test.json 
"10"

# 查看math
$ jq '.score.math' test.json
"85"

Consulta vários conjuntos de dados, os dados são os seguintes:

$ cat test.json 
[{
    
    "gender":"man","name":"zhangsan","age":10,"score":{
    
    "math":85,"English":86,"Chinese":87}},{
    
    "gender":"man","name":"lisi","age":9,"score":{
    
    "math":80,"English":81,"Chinese":82}},{
    
    "gender":"man","name":"wangwu","age":11,"score":{
    
    "math":85,"English":84,"Chinese":87}},{
    
    "gender":"female","name":"lili","age":11,"score":{
    
    "math":85,"English":88,"Chinese":90}}]

$ cat test.json | jq  .
[
  {
    
    
    "gender": "man",
    "name": "zhangsan",
    "age": 10,
    "score": {
    
    
      "math": 85,
      "English": 86,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "man",
    "name": "lisi",
    "age": 9,
    "score": {
    
    
      "math": 80,
      "English": 81,
      "Chinese": 82
    }
  },
  {
    
    
    "gender": "man",
    "name": "wangwu",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 84,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "female",
    "name": "lili",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 88,
      "Chinese": 90
    }
  }
]
$ cat test.json |  jq '.[0]'
{
    
    
  "gender": "man",
  "name": "zhangsan",
  "age": 10,
  "score": {
    
    
    "math": 85,
    "English": 86,
    "Chinese": 87
  }
}

$ cat test.json |  jq '.[1]'
{
    
    
  "gender": "man",
  "name": "lisi",
  "age": 9,
  "score": {
    
    
    "math": 80,
    "English": 81,
    "Chinese": 82
  }
}

2.3, filtrar dados JSON

Use jq para filtrar parte dos dados JSON com base em determinadas condições

$ cat test.json |  jq '.[] | select(.age > 10)'
{
    
    
  "gender": "man",
  "name": "wangwu",
  "age": 11,
  "score": {
    
    
    "math": 85,
    "English": 84,
    "Chinese": 87
  }
}
{
    
    
  "gender": "female",
  "name": "lili",
  "age": 11,
  "score": {
    
    
    "math": 85,
    "English": 88,
    "Chinese": 90
  }
}

$ cat test.json |  jq '.[] | select(.score.math < 85)'
{
    
    
  "gender": "man",
  "name": "lisi",
  "age": 9,
  "score": {
    
    
    "math": 80,
    "English": 81,
    "Chinese": 82
  }
}


$ cat test.json |  jq '.[] | select(.score.math < 80)'

2.4. Editar dados JSON

Certos campos ou valores em dados JSON podem ser editados usando jq.

$ cat test.json | jq '.[0].age'
10

$ cat test.json | jq '.[0].age += 1'
[
  {
    
    
    "gender": "man",
    "name": "zhangsan",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 86,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "man",
    "name": "lisi",
    "age": 9,
    "score": {
    
    
      "math": 80,
      "English": 81,
      "Chinese": 82
    }
  },
  {
    
    
    "gender": "man",
    "name": "wangwu",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 84,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "female",
    "name": "lili",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 88,
      "Chinese": 90
    }
  }
]

$ cat test.json 
[{
    
    "gender":"man","name":"zhangsan","age":10,"score":{
    
    "math":85,"English":86,"Chinese":87}},{
    
    "gender":"man","name":"lisi","age":9,"score":{
    
    "math":80,"English":81,"Chinese":82}},{
    
    "gender":"man","name":"wangwu","age":11,"score":{
    
    "math":85,"English":84,"Chinese":87}},{
    
    "gender":"female","name":"lili","age":11,"score":{
    
    "math":85,"English":88,"Chinese":90}}]

Deve-se observar que o arquivo original não foi modificado.

3. Outro uso

3.1, caractere vertical|

Usando |operadores podemos combinar dois filtros. Funciona de forma semelhante ao caractere de barra vertical em sistemas Unix. A saída do filtro à esquerda é passada para o filtro à direita.

3.2, keysfunção

A função keys obtém todas as chaves do objeto JSON. A função keys retorna uma lista contendo os nomes de todas as chaves no objeto JSON. O índice de dados obtido para vários conjuntos de dados é o seguinte:

$ cat test.json | jq '. | keys'
[
  0,
  1,
  2,
  3
]

Obtenha um determinado conjunto de chaves de dados

$ cat test.json | jq '.[0] | keys'
[
  "age",
  "gender",
  "name",
  "score"
]

$ cat test.json | jq '.[0].score | keys'
[
  "Chinese",
  "English",
  "math"
]

3.3, lengthfunção

Retorna o comprimento de um array ou string.

$ cat test.json | jq '. | length'
4

$ cat test.json | jq '.[0] | length'
4

$ cat test.json | jq '.[0].score | length'
3

$ cat test.json | jq '.[0].name | length'
8

3.4, mapfunção

Execute uma função em cada elemento de um array e retorne um novo array.

$ cat test.json | jq '. | map(keys)'
[
  [
    "age",
    "gender",
    "name",
    "score"
  ],
  [
    "age",
    "gender",
    "name",
    "score"
  ],
  [
    "age",
    "gender",
    "name",
    "score"
  ],
  [
    "age",
    "gender",
    "name",
    "score"
  ]
]

$ cat test.json | jq '. | map(length)'
[
  4,
  4,
  4,
  4
]

3.5, selectfunção

Filtra cada elemento de um array e retorna um novo array.
Consulte 2.3

3.6. if-then-elseDeclaração

if-then-elseInstruções para realizar diferentes operações com base em condições. A sintaxe é a seguinte:

if CONDITION then EXPRESSION1 else EXPRESSION2 end

CONDIÇÃO é uma expressão condicional, que pode ser uma comparação, lógica ou outro tipo de expressão. Se CONDITION for verdadeira, execute EXPRESSION1, caso contrário execute EXPRESSION2. EXPRESSION1 e EXPRESSION2 podem ser qualquer expressão jq, incluindo chamadas de função, referências de variáveis, operações matemáticas, etc.

$ cat test.json | jq '.[0].name= if .[0].age >5 then "first" else "second" end'
[
  {
    
    
    "gender": "man",
    "name": "first",
    "age": 10,
    "score": {
    
    
      "math": 85,
      "English": 86,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "man",
    "name": "lisi",
    "age": 9,
    "score": {
    
    
      "math": 80,
      "English": 81,
      "Chinese": 82
    }
  },
  {
    
    
    "gender": "man",
    "name": "wangwu",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 84,
      "Chinese": 87
    }
  },
  {
    
    
    "gender": "female",
    "name": "lili",
    "age": 11,
    "score": {
    
    
      "math": 85,
      "English": 88,
      "Chinese": 90
    }
  }
]

3.7. joinFunção

Concatena todos os elementos de um array em uma string. A função oin só pode ser usada para matrizes de strings, não para outros tipos de matrizes.
test01.json

{
    
    
  "name": "Alice",
  "hobbies": ["reading", "singing", "dancing"]
}
cat test01.json | jq '.hobbies | join(",")'
"reading,singing,dancing"

3.8. splitFunção

Divida uma string em substrings e armazene-as em um array.

$ cat test.json | jq '.[0].name | split("")'
[
  "z",
  "h",
  "a",
  "n",
  "g",
  "s",
  "a",
  "n"
]

$ cat test.json | jq '.[0].name | split("n")'
[
  "zha",
  "gsa",
  ""
]

3.9. max和minFunção

Retorna o valor máximo ou mínimo em uma matriz ou conjunto de números

$ cat test.json | jq '. | map(.score.math) | max'
85

$ cat test.json | jq '. | map(.score.math) | min'
80

$ cat test.json | jq '. | map(.age) | max'
11

3.10. flattenFunção

Converter array multidimensional em array unidimensional

test02.json

$ cat test02.json 
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
$ cat test02.json | jq '. | flatten'
[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9
]

3.11. sortFunção

Classificar elementos em uma matriz

$ cat test.json | jq '. | map(.age) | sort'
[
  9,
  10,
  11,
  11
]

$ cat test.json | jq '. | map(.score.Chinese) | sort'
[
  82,
  87,
  87,
  90
]

3.12. group_byFunção

Agrupar elementos em um array por uma chave

# 依据age分组
$ cat test.json | jq 'group_by(.age)'
[
  [
    {
    
    
      "gender": "man",
      "name": "lisi",
      "age": 9,
      "score": {
    
    
        "math": 80,
        "English": 81,
        "Chinese": 82
      }
    }
  ],
  [
    {
    
    
      "gender": "man",
      "name": "zhangsan",
      "age": 10,
      "score": {
    
    
        "math": 85,
        "English": 86,
        "Chinese": 87
      }
    }
  ],
  [
    {
    
    
      "gender": "man",
      "name": "wangwu",
      "age": 11,
      "score": {
    
    
        "math": 85,
        "English": 84,
        "Chinese": 87
      }
    },
    {
    
    
      "gender": "female",
      "name": "lili",
      "age": 11,
      "score": {
    
    
        "math": 85,
        "English": 88,
        "Chinese": 90
      }
    }
  ]
]

3.13. uniqueFunção

Usado para remover elementos duplicados dos dados de entrada

test03.json

$ cat test03.json 
[1, 2, 3, 1, 2, 4, 5, 3]
$ cat test03.json | jq '. | unique'
[
  1,
  2,
  3,
  4,
  5
]

3.14. to_entries和from_entriesFunção

Converte um objeto em uma matriz de pares de valores-chave ou uma matriz de pares de valores-chave em um objeto.

$ cat test.json | jq '.[0] |to_entries'
[
  {
    
    
    "key": "gender",
    "value": "man"
  },
  {
    
    
    "key": "name",
    "value": "zhangsan"
  },
  {
    
    
    "key": "age",
    "value": 10
  },
  {
    
    
    "key": "score",
    "value": {
    
    
      "math": 85,
      "English": 86,
      "Chinese": 87
    }
  }
]

test04.json

$ cat test04.json 
[
  {
    
    
    "key": "gender",
    "value": "man"
  },
  {
    
    
    "key": "name",
    "value": "zhangsan"
  },
  {
    
    
    "key": "age",
    "value": 10
  },
  {
    
    
    "key": "score",
    "value": {
    
    
      "math": 85,
      "English": 86,
      "Chinese": 87
    }
  }
]
$ cat test04.json | jq '. |from_entries'
{
    
    
  "gender": "man",
  "name": "zhangsan",
  "age": 10,
  "score": {
    
    
    "math": 85,
    "English": 86,
    "Chinese": 87
  }
}

3.15. containsFunção

Verifique se um array contém um elemento específico

$ cat test.json | jq '.[0].name | contains("z")'
true

$ cat test.json | jq '.[0].name | contains("l")'
false

3.16, startswith和endswithfunção

Verifique se uma string começa ou termina com um prefixo ou sufixo específico

$ cat test.json | jq '.[0].name | startswith("zh")'
true

$ cat test.json | jq '.[0].name | startswith("li")'
false

$ cat test.json | jq '.[0].name | endswith("san")'
true

$ cat test.json | jq '.[0].name | endswith("hua")'
false

Documentação de referência

1、https://mp.weixin.qq.com/s/U1VwJGFVkrUyv3jMegapCg

2、https://mp.weixin.qq.com/s/45-ztTx2scbNY5u7NQzeIA

3、https://www.cnblogs.com/FunTester/p/14713957.html

4、https://blog.csdn.net/w727655308/article/details/121207345

Acho que você gosta

Origin blog.csdn.net/yuelai_217/article/details/131533266
Recomendado
Clasificación