AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 429348
Accepted
DonJ
DonJ
Asked: 2018-03-10 13:27:08 +0800 CST2018-03-10 13:27:08 +0800 CST 2018-03-10 13:27:08 +0800 CST

filtro jq: mostra toda a estrutura com seleção

  • 772

Eu tenho o seguinte file1 json:

{
  "name": "eye",
  "attributes": [
    {
      "name": "Width",
      "value": "1920"
    },
    {
      "name": "Height",
      "value": "1080"
    },
    {
      "name": "WinKeyMapping",
      "value": "leftwin"
    }
  ],
  "starts": [
    {
      "name": "step1",
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        },
        {
          "name": "Test",
          "value": "none"
        }
      ]
    }
  ]
}

e seguinte filtro:

$ jq '.starts[].attributeList[]|select(.name=="Command")' file1
{
  "name": "Command",
  "value": "bash"
}
$

como eu poderia obter toda a estrutura para esta seleção?

saída esperada:

{
  "starts": [
    {
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        }
      ]
    }
  ]
}
json jq
  • 3 3 respostas
  • 2862 Views

3 respostas

  • Voted
  1. Best Answer
    RomanPerekhrest
    2018-03-10T13:43:31+08:002018-03-10T13:43:31+08:00

    Direto com jq:

    jq '{ starts: [ { attributeList: (.starts[].attributeList 
                                      | map(select(.name == "Command"))) }] }' file.json
    

    A saída:

    {
      "starts": [
        {
          "attributeList": [
            {
              "name": "Command",
              "value": "bash"
            }
          ]
        }
      ]
    }
    
    • 2
  2. fearphage
    2018-04-13T05:48:58+08:002018-04-13T05:48:58+08:00

    Aqui estão duas opções para obter a saída desejada.

    Você pode excluir as chaves que não deseja:

    jq 'del(.attributes, .name) | 
      .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'
    

    Ou você pode selecionar apenas a(s) chave(s) que deseja:

    jq 'to_entries | map(select(.key == "starts")) | from_entries | 
      .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'
    

    Ambos dão o mesmo resultado. Além disso, se você quiser startse endsno último caso, basta adicionar ordeclarações adicionais: map(select((.key == "starts") or (.key == "ends"))).

    • 0
  3. Kusalananda
    2021-07-12T14:48:35+08:002021-07-12T14:48:35+08:00

    Uma abordagem mais genérica com jq:

    def pick_out(q): path(q) as $path | ($path | length) as $length |
        delpaths(
            [
                paths(..) |
                select(length <= $length and $path[0:length] != . )
            ]
        );
    

    Esta é uma jqfunção que exclui todos os caminhos do documento que não estão em nenhum lugar no caminho do argumento fornecido, que pode ser uma select()chamada.

    Salvando isso em pick_out.jq, podemos usá-lo assim:

    jq 'include "pick_out";
        pick_out(
            .starts[].attributeList[] | select(.name == "Command")
        )' file.json
    

    A saída:

    {
      "starts": [
        {
          "attributeList": [
            {
              "name": "Command",
              "value": "bash"
            }
          ]
        }
      ]
    }
    
    • 0

relate perguntas

  • Matriz JSON para bash variáveis ​​usando jq

  • chave de impressão jq e valor para todos no subobjeto

  • jq adicionar ou atualizar um valor com vários --arg

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    ssh Não é possível negociar: "nenhuma cifra correspondente encontrada", está rejeitando o cbc

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    Como descarregar o módulo do kernel 'nvidia-drm'?

    • 13 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Wong Jia Hau ssh-add retorna com: "Erro ao conectar ao agente: nenhum arquivo ou diretório" 2018-08-24 23:28:13 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST
  • Martin Hope
    Bagas Sanjaya Por que o Linux usa LF como caractere de nova linha? 2017-12-20 05:48:21 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve