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 / 750864
Accepted
Velin Budinov
Velin Budinov
Asked: 2023-07-07 16:32:55 +0800 CST2023-07-07 16:32:55 +0800 CST 2023-07-07 16:32:55 +0800 CST

Como formatar uma string JSON como uma tabela usando jq?

  • 772

Preciso converter uma string JSON usando jq, conforme mostrado abaixo, em um formato de tabela para exibir a saída no terminal.

{
  "results": [
    [
      {
        "field": "@timestamp",
        "value": "2023-07-03 08:28:00.000"
      },
      {
        "field": "CpuReserved",
        "value": "8192.0"
      },
      {
        "field": "CpuUtilized",
        "value": "4056.412942708333"
      },
      {
        "field": "MemoryReserved",
        "value": "61440"
      },
      {
        "field": "MemoryUtilized",
        "value": "4311"
      },
      {
        "field": "@ptr",
        "value": "CpABClUKUTE0NjcxNzAzNzI0NzovYXdzL2Vjcy9jb250YWluZXJpbnNpZ2h0cy9pcmwtaW5mcmEtc2hhcmVkLWplbmtpbnMtbWFpbi9wZXJmb3JtYW5jZRABEjUaGAIGSaxosQAAAAAd+TFeAAZKKHIwAAABEiABKIDF9taRMTDA7v3WkTE4BkC9NEjNPFCBIRgAEAAYAQ=="
      }
    ],
    [
      {
        "field": "@timestamp",
        "value": "2023-07-03 08:28:00.000"
      },
      {
        "field": "CpuReserved",
        "value": "8192.0"
      },
      {
        "field": "CpuUtilized",
        "value": "4056.412942708333"
      },
      {
        "field": "MemoryReserved",
        "value": "61440"
      },
      {
        "field": "MemoryUtilized",
        "value": "4311"
      },
      {
        "field": "@ptr",
        "value": "CpABClUKUTE0NjcxNzAzNzI0NzovYXdzL2Vjcy9jb250YWluZXJpbnNpZ2h0cy9pcmwtaW5mcmEtc2hhcmVkLWplbmtpbnMtbWFpbi9wZXJmb3JtYW5jZRABEjUaGAIGSaxosQAAAAAd+TFeAAZKKHIwAAABEiABKIDF9taRMTDA7v3WkTE4BkC9NEjNPFCBIRgAEAEYAQ=="
      }
    ]
  ]
}

O que eu quero exibir no terminal é o seguinte:

@timestamp                CpuReserved  CpuUtilized         MemoryReserved   MemoryUtilized  
==========================================================================================
2023-07-03 08:16:00.000   8192.0       410.5300065104166   61440            1417
2023-07-03 08:15:00.000   8192.0       702.310791015625    61440            792

Alguém pode me guiar na direção certa?

json
  • 4 4 respostas
  • 586 Views

4 respostas

  • Voted
  1. Best Answer
    Stéphane Chazelas
    2023-07-07T17:07:01+08:002023-07-07T17:07:01+08:00

    Talvez:

    $ jq -c '.results[]|map(.key=.field)|from_entries|del(."@ptr")' file.json |
       mlr --ijson --opprint --barred cat
    +-------------------------+-------------+-------------------+----------------+----------------+
    | @timestamp              | CpuReserved | CpuUtilized       | MemoryReserved | MemoryUtilized |
    +-------------------------+-------------+-------------------+----------------+----------------+
    | 2023-07-03 08:28:00.000 | 8192.0      | 4056.412942708333 | 61440          | 4311           |
    | 2023-07-03 08:28:00.000 | 8192.0      | 4056.412942708333 | 61440          | 4311           |
    +-------------------------+-------------+-------------------+----------------+----------------+
    

    Sem --barred, fica assim:

    @̲t̲i̲m̲e̲s̲t̲a̲m̲p̲               C̲p̲u̲R̲e̲s̲e̲r̲v̲e̲d̲  C̲p̲u̲U̲t̲i̲l̲i̲z̲e̲d̲        M̲e̲m̲o̲r̲y̲R̲e̲s  ̲e̲r̲v̲e̲d̲ M̲e̲m̲o̲r̲y̲U̲t̲i̲l̲i̲z̲e̲d̲
    2023-07-03 08:28:00.000 8192.0 4056.412942708333 61440 4311
    2023-07-03 08:28:00.000 8192.0 4056.412942708333 61440 4311
    

    Você também pode canalizar a saída desse jqcomando para vd -f json( VisiData ) em vez de mlr( Miller ) para obter um visualizador de tabela interativo.

    Esses usam jqpara extrair as informações e mlrapenas para formatar a tabela. Há alguma sobreposição entre o conjunto de recursos de jqe o de mlr. Por exemplo, você também pode remover a @ptrcoluna com mlr's cut:

    jq -c '.results[]|map(.key=.field)|from_entries' file.json |
      mlr --ijson --opprint cut -xf @ptr
    

    Esse jqcomando, dividido e comentado:

    jq -c '
      .results[] | # iterate over the elements of the .results array 
                   # (which are also arrays)
    
      map(.key=.field) | # for each of those arrays, transform the
                         # elements (which are objects) by adding a 
                         # field of key "key" with same value as that
                         # with "field" key in each, as that's what
                         # from_entries needs
    
      from_entries | # transforms those [{"key":"foo","value":"bar"}]
                     # (the "field" field is ignored) to {"foo":"bar"}
    
      del(."@ptr") # deletes the field with key "@ptr" from those
                   # objects' file.json
    

    O resultado não é JSON, mas vários JSONs concatenados juntos, mas ambos jqsuportam mlrisso. Com -c(compacto), isso é NDJSON (JSON delimitado por nova linha), onde temos um JSON por linha, também suportado por vd. Para obter o JSON adequado, precisaríamos:

    jq -c '.results|map(map(.key=.field)|from_entries|del(."@ptr"))' file.json
    

    Onde usamos mapno .resultsarray para que resulte em outro array JSON em vez de iterar sobre os elementos. Portanto, o resultado final é um grande array. Isso também é suportado por jq(obviamente porque é JSON adequado) mlre vd, é um pouco mais longo para digitar e significa que essas ferramentas precisam ler até o fechamento ]no final antes de terem algo para mastigar. Na prática, não verifiquei se isso fazia alguma diferença em termos de desempenho.

    • 11
  2. kev
    2023-07-07T17:29:34+08:002023-07-07T17:29:34+08:00

    Ainda outra:

    $ jq -r '.results|map(map({key:.field,value}|select(.key!="@ptr"))|from_entries)|(.[0]|keys_unsorted) as $keys|([$keys]+map([.[$keys[]]]))[]|@csv' input.json | xsv table
    @timestamp               CpuReserved  CpuUtilized        MemoryReserved  MemoryUtilized
    2023-07-03 08:28:00.000  8192.0       4056.412942708333  61440           4311
    2023-07-03 08:28:00.000  8192.0       4056.412942708333  61440           4311
    

    Notas:

    • from_entriesconverterá uma matriz de pares chave-valor em um objeto.
    • Para converter uma matriz de objetos em csv: Exibir detalhes .
    • xsv tableé apenas para impressão bonita, você pode removê-lo.
    • 3
  3. Velin Budinov
    2023-07-07T17:54:30+08:002023-07-07T17:54:30+08:00

    Acho que encontrei a resposta:

    jq -r '([ "@timestamp", "CpuReserved", "CpuUtilized", "MemoryReserved", "MemoryUtilized"] | (., map(length*"-"))), ( .results[] | [.[0,1,2,3,4].value] ) | @tsv' |column -ts $'\t'
    @timestamp               CpuReserved  CpuUtilized         MemoryReserved  MemoryUtilized
    ----------               -----------  -----------         --------------  --------------
    2023-07-03 08:28:00.000  8192.0       4056.412942708333   61440           4311
    2023-07-03 08:28:00.000  8192.0       4056.412942708333   61440           4311
    2023-07-03 08:27:00.000  8192.0       1056.0744270833331  61440           4436
    2023-07-03 08:27:00.000  8192.0       1056.0744270833331  61440           4436
    2023-07-03 08:26:00.000  8192.0       2756.6764583333334  61440           5138
    2023-07-03 08:26:00.000  8192.0       2756.6764583333334  61440           5138
    2023-07-03 08:25:00.000  8192.0       5715.494895833333   61440           6600
    2023-07-03 08:25:00.000  8192.0       5715.494895833333   61440           6600
    2023-07-03 08:24:00.000  8192.0       7977.704166666666   61440           8451
    2023-07-03 08:24:00.000  8192.0       7977.704166666666   61440           8451
    2023-07-03 08:23:00.000  8192.0       7288.051666666666   61440           4757
    2023-07-03 08:23:00.000  8192.0       7288.051666666666   61440           4757
    2023-07-03 08:22:00.000  8192.0       4286.02375          61440           4815
    2023-07-03 08:22:00.000  8192.0       4286.02375          61440           4815
    2023-07-03 08:21:00.000  8192.0       3357.523776041666   61440           2146
    2023-07-03 08:21:00.000  8192.0       3357.523776041666   61440           2146
    2023-07-03 08:20:00.000  8192.0       990.2647916666666   61440           1692
    2023-07-03 08:20:00.000  8192.0       990.2647916666666   61440           1692
    2023-07-03 08:19:00.000  8192.0       4533.409375         61440           1816
    2023-07-03 08:19:00.000  8192.0       4533.409375         61440           1816
    2023-07-03 08:18:00.000  8192.0       939.4855208333333   61440           1810
    2023-07-03 08:18:00.000  8192.0       939.4855208333333   61440           1810
    2023-07-03 08:17:00.000  8192.0       4770.659791666667   61440           1924
    2023-07-03 08:17:00.000  8192.0       4770.659791666667   61440           1924
    2023-07-03 08:16:00.000  8192.0       410.5300065104166   61440           1417
    2023-07-03 08:16:00.000  8192.0       410.5300065104166   61440           1417
    2023-07-03 08:15:00.000  8192.0       702.310791015625    61440           792
    2023-07-03 08:15:00.000  8192.0       702.310791015625    61440           792
    2023-07-03 08:14:00.000  8192.0       0.0                 61440           0
    2023-07-03 08:14:00.000  8192.0       0.0                 61440           0
    
    • 3
  4. glenn jackman
    2023-07-07T22:09:01+08:002023-07-07T22:09:01+08:00

    Outra tomada que usa jqpara emitir valores separados por tabulações e columnembelezá-lo

    jq -r '
      .results
      | first as $first
      | [$first | map(.field)] + [.[] | map(.value)]
      | map(.[:-1])[]
      | @tsv
    ' file.json | column -t -s $'\t'
    
    @timestamp               CpuReserved  CpuUtilized        MemoryReserved  MemoryUtilized
    2023-07-03 08:28:00.000  8192.0       4056.412942708333  61440           4311
    2023-07-03 08:28:00.000  8192.0       4056.412942708333  61440           4311
    
    • 1

relate perguntas

  • Usando jq para obter uma saída estruturada

  • Extraia o elemento da matriz json com base em um valor de subelemento

  • Como converter string json incorporada (entre aspas) em json

  • 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

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

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

    • 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

    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
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • 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
    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

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