Nushell:レコードリストをテーブルに変換

Nushell:レコードリストをテーブルに変換

明確性の注意:元の名前は「Nushell:Convert List to Table」(一部の検索エンジンではこの単語の最初の結果として表示されます)でしたが、このスタックオーバーフローの質問より良い「テーブルリスト」の例になります。


同様のレコードのリストをテーブルに変換する慣用的な方法はNushellにありますか?

私は一緒に働いていますスタック交換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は、ほとんどの質問に対して空のフィールドを返すために帯域幅を無駄にする必要はありません。

しかし、結果的に$questionsNushellの一つになりましたlist<any>。これは次のことを意味します。

> $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"

ベストアンサー1

これで、公式の説明に従って疑問符演算子を使用できます。文書:

❯ $questions | group-by closed_reason?
╭───────────┬───────────────────────────────────────────────────────────────╮
│           │ ╭───┬─────────────┬─────────────────────────┬───────────────╮ │
│ Duplicate │ │ # │    tags     │          title          │ closed_reason │ │
│           │ ├───┼─────────────┼─────────────────────────┼───────────────┤ │
│           │ │ 0 │ ╭───┬─────╮ │ tar through ssh session │ Duplicate     │ │
│           │ │   │ │ 0 │ ssh │ │                         │               │ │
│           │ │   │ │ 1 │ tar │ │                         │               │ │
│           │ │   │ ╰───┴─────╯ │                         │               │ │
│           │ ╰───┴─────────────┴─────────────────────────┴───────────────╯ │
╰───────────┴───────────────────────────────────────────────────────────────╯

おすすめ記事