Skip to content

Instantly share code, notes, and snippets.

@joewiz
Last active February 5, 2024 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joewiz/b4ff13c72b1b1a1bfb3b419097e96870 to your computer and use it in GitHub Desktop.
Save joewiz/b4ff13c72b1b1a1bfb3b419097e96870 to your computer and use it in GitHub Desktop.
Convert XQuery maps to CSV (or TSV)
xquery version "3.1";
(: Convert a sequence of XQuery maps into CSV or TSV.
: Each map becomes one row.
: The entries' keys become column headers.
:)
declare variable $local:default-options :=
map {
(: Character to separate cells with :)
"cell-separator": ",",
(: Character to separate rows with :)
"row-separator": "
",
(: Character to wrap cells whose values contain the cell separator :)
"escape-wrapper": '"',
(: Sort keys alphabetically by header, or leave in implementation-defined order :)
"sort-keys": false()
}
;
declare function local:maps-to-csv($maps as map(xs:string, xs:string)*) as xs:string {
local:maps-to-csv($maps, $local:default-options)
};
declare function local:maps-to-tsv($maps as map(xs:string, xs:string)*) as xs:string {
local:maps-to-csv($maps, map { "cell-separator": "	" })
};
declare function local:maps-to-csv($maps as map(xs:string, xs:string)*, $custom-options as map(*)) as xs:string {
let $options := map:merge(($custom-options, $local:default-options), map { "duplicates": "use-first" })
let $headers := $maps => for-each(map:keys#1) => distinct-values() => (function($values) { if ($custom-options?sort-keys) then sort($values) else $values })()
let $header-row := $headers => string-join($options?cell-separator)
let $body-rows :=
for $map in $maps
let $cells :=
for $header in $headers
let $cell := map:get($map, $header)
return
if (empty($cell)) then
""
else if (contains($cell, $options?cell-separator)) then
$options?escape-wrapper || $cell || $options?escape-wrapper
else
$cell
return
$cells => string-join($options?cell-separator)
return
($header-row, $body-rows) => string-join($options?row-separator)
};
(: The function is forgiving if maps have varying sets of keys or if the cells contain the cell separator character :)
(
map{ "Title": "The Future of Ideas", "Author": "Lessig, L." },
map{ "Author": "Walls, J.", "Title": "The Glass Castle" },
map{ "City": "Milwaukee", "State": "Wisconsin" }
)
=> local:maps-to-csv()
Title Author City State
The Future of Ideas Lessig, L.
The Glass Castle Walls, J.
Milwaukee Wisconsin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment