消歧说明:我最初将这个标题命名为“Nushell:将列表转换为表格”(一些搜索引擎将此作为这些单词的第一个结果),但是这个 Stack Overflow 问题可能是一个更好的“列表到表格”示例。
有没有一种惯用的方法可以将类似记录的列表转换为 Nushell 中的表?
我正在使用Stack Exchange API并获取以下结果:
let questions = ('[
{
"tags":
[
"nushell"
],
"title": "Nushell: Convert list to table"
},
{
"tags":
[
"ssh",
"tar"
],
"title": "tar through ssh session",
"closed_reason": "Duplicate"
}
]' | from json)
请注意,closed_reason
只有已关闭的问题才会返回,当然。这是有道理的——对于大多数问题,API 无需浪费带宽返回空字段。
但这样一来,$questions
就变成了list<any>
Nushell中的一个。这意味着像这样的操作:
> $questions | group-by closed_reason
...导致(逻辑上)cannot find column
错误。
所有结果都需要具有相同的结构才能正常工作。例如,如果所有结果都有closed_reason
',像这样:
let questions = ('[
{
"tags":
[
"nushell"
],
"title": "Nushell: Convert list to table",
"closed_reason": ""
},
{
"tags":
[
"ssh",
"tar"
],
"title": "tar through ssh session",
"closed_reason": "Duplicate"
}
]' | from json)
然后$questions | describe
变成:
table<tags: list<string>, title: string, closed_reason: string>
并且$questions | group-by closed_reason
会工作。
有没有办法将列表转换/“规范化”为表格?
我已经尝试过(使用原始list<any>
结果):
> $questions | table | group-by closed_reason
# obviously doesn't work, since the table command is just for rendering
# but worth a shot
> $questions | to csv | from csv | group-by closed_reason
# works, but loses the tag lists
> $questions | transpose | transpose | headers | reject column0 | to json
# Almost works, but still results in a list<any>
# since the first question's closed_reason becomes null
> $questions | transpose | transpose | headers | reject column0 | group-by closed_reason
# results in "can't convert nothing to string"