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

后端 未结 4 1525
闹比i
闹比i 2020-12-04 13:02

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.

4条回答
  •  半阙折子戏
    2020-12-04 13:38

    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'
    

提交回复
热议问题