To get the names of columns in a table or the keys of a record you can use the columns command.
The command returns a list of string values that are the column or key names.
When the input is table the column names are returned, and when the input is a record the names of the keys are returned.
In the following example code the columns command is used with a record and table:
use std/assert
# columns on a record return the record keys.
let record = {alias: mrhaki name: "Hubert Klein Ikkink" country: "The Netherlands"}
assert equal ($record | columns) [alias name country]
# columns used with a table return the column names.
let table = [
[name ship age];
["Jack Sparrow" "Black Pearl" 40]
["Will Turner" "Flying Dutchman" 35]
]
assert equal ($table | columns) [name ship age]
Output of commands that return a table sometimes do not fit on the screen.
With the columns command the column names can be fetched and with select the number of columns in the output can be less so it fits on the screen.
In the following examples several uses of columns are shown:
# Using columns to get column names for ls command output.
assert equal (ls | columns) [name type size modified]
# Using --long option gets more column names.
# Output can differ per operating system, this is for MacOS.
(assert equal (ls --long | columns)
[name type target readonly mode
num_links inode user group
size created accessed modified])
let url = "https://httpbin.org/json"
# JSON response https://httpbin.org/json
# {
# "slideshow": {
# "author": "Yours Truly",
# "date": "date of publication",
# "slides": [
# {
# "title": "Wake up to WonderWidgets!",
# "type": "all"
# },
# {
# "items": [
# "Why <em>WonderWidgets</em> are great",
# "Who <em>buys</em> WonderWidgets"
# ],
# "title": "Overview",
# "type": "all"
# }
# ],
# "title": "Sample Slide Show"
# }
# }
let url_content = http get $url
assert equal ($url_content | columns) [slideshow]
(assert equal ($url_content | get slideshow | columns)
[author date slides title])
(assert equal ($url_content | get slideshow | select author title)
{ author: "Yours Truly" title: "Sample Slide Show" })
Written with Nushell 0.108.0.