Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a JSON string as a table using jq?

Tags:

json

bash

jq

Just started out with Bash scripting and stumbled upon jq to work with JSON.

I need to transform a JSON string like below to a table for output in the terminal.

[{     "name": "George",     "id": 12,     "email": "[email protected]" }, {     "name": "Jack",     "id": 18,     "email": "[email protected]" }, {     "name": "Joe",     "id": 19,     "email": "[email protected]" }] 

What I want to display in the terminal:

ID        Name ================= 12        George 18        Jack 19        Joe 

Notice how I don't want to display the email property for each row, so the jq command should involve some filtering. The following gives me a plain list of names and id's:

list=$(echo "$data" | jq -r '.[] | .name, .id') printf "$list" 

The problem with that is, I cannot display it like a table. I know jq has some formatting options, but not nearly as good as the options I have when using printf. I think I want to get these values in an array which I can then loop through myself to do the formatting...? The things I tried give me varying results, but never what I really want.

Can someone point me in the right direction?

like image 549
Rein Avatar asked Aug 25 '16 07:08

Rein


People also ask

Can we convert JSON to table?

Given an HTML document containing JSON data and the task is to convert JSON data into a HTML table. Approach 1: Take the JSON Object in a variable. Call a function which first adds the column names to the < table > element.

Does jq use JSONPath?

JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.

Can jq write JSON?

jq is an amazing little command line utility for working with JSON data.

What is jq format?

jq is a free open source JSON processor that is flexible and straightforward to use. It allows users to display a JSON file using standard formatting, or to retrieve certain records or attribute-value pairs from it.


1 Answers

Using the @tsv filter has much to recommend it, mainly because it handles numerous "edge cases" in a standard way:

.[] | [.id, .name] | @tsv 

Adding the headers can be done like so:

jq -r '["ID","NAME"], ["--","------"], (.[] | [.id, .name]) | @tsv' 

The result:

ID  NAME --  ------ 12  George 18  Jack 19  Joe 

length*"-"

To automate the production of the line of dashes:

jq -r '(["ID","NAME"] | (., map(length*"-"))), (.[] | [.id, .name]) | @tsv' 
like image 162
peak Avatar answered Sep 23 '22 18:09

peak