recordnushell

How to convert Record to Table in Nushell?


I found how to convert Table to Record using the following code here.

let fruits_original = [[key, value]; [apple 10] [banana 42] [mango 5]]
let fruits = $fruits_original | reduce -f {} {|it, acc| $acc | upsert $it.key $it.value }
$fruits == { "apple": 10, "banana": 42, "mango": 5 }
# output is true

But how can I convert it back?

let fruits_original = { "apple": 10, "banana": 42, "mango": 5 }
# TODO: convert Record to Table
$fruits == [[key, value]; [apple 10] [banana 42] [mango 5]]

I'm trying to convert Record to Table to access the values of it (treat as key-value pairs).

Thanks for your help.


Solution

  • You could use transpose to convert in both directions. For the first one, table to record, use the --header-row and --as-record (or -r and -d) flags. For the second one, provide key and value as column names:

    let fruits_original = [[key, value]; [apple 10] [banana 42] [mango 5]]
    let fruits = $fruits_original | transpose -rd
    $fruits == { "apple": 10, "banana": 42, "mango": 5 }
    # output is true
    
    let fruits_original = { "apple": 10, "banana": 42, "mango": 5 }
    let fruits = $fruits_original | transpose key value
    $fruits == [[key, value]; [apple 10] [banana 42] [mango 5]]
    # output is true