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 │ │                         │               │ │
│           │ │   │ ╰───┴─────╯ │                         │               │ │
│           │ ╰───┴─────────────┴─────────────────────────┴───────────────╯ │
╰───────────┴───────────────────────────────────────────────────────────────╯

답변2

불행히도 나는 nu껍질에 익숙하지 않습니다. 그러나 데이터를 JSON으로 확실히 전달하고 jq빈 문자열 값이 있는 누락된 키를 추가한 다음 이를 다시 셸의 내부 표현으로 변환할 수 있습니다.

questions여기서는 변수를 업데이트 하지만 불필요하게 데이터를 앞뒤로 변환하는 대신 jq원래 명령에 명령을 태그 할 수 있습니다.let

let questions = ($questions | to json | jq '.[].closed_reason += ""' | from json)

그런 다음 다음과 같이 그룹화할 수 있습니다 closed_reason.

〉$questions | group-by closed_reason
╭───────────┬───────────────╮
│           │ [table 1 row] │
│ Duplicate │ [table 1 row] │
╰───────────┴───────────────╯

답변3

마침내 답을 찾았습니다. help --find def나는 적절하게 이름이 지정되었지만 Nushell 책에서는 참조되지 않은 명령을 발견했을 때 완전히 다른 것을 찾고 있었습니다. default이는 기본적으로 다음과 동일한 작업을 수행하기 위한 Nushell 내장 명령입니다.@Kusalananda 추천그리고 jq.

따라서 질문의 예는 다음과 같이 수정할 수 있습니다.

> $questions | default "" closed_reason | group-by closed_reason
╭───────────┬───────────────╮
│           │ [table 1 row] │
│ Duplicate │ [table 1 row] │
╰───────────┴───────────────╯

결과는 실제 Nushell 테이블 개체입니다.

> $questions | default "" closed_reason | describe
table<tags: list<string>, title: string, closed_reason: string>

이를 통해 Stack API에서 일부 슬라이싱 및 다이싱 작업을 시작할 수 있습니다.

> $questions |
      default "" closed_reason | 
      where closed_reason == "Duplicate" |
      update tags { $in.tags | str collect ','}
      
╭───┬─────────┬─────────────────────────┬───────────────╮
│ # │  tags   │          title          │ closed_reason │
├───┼─────────┼─────────────────────────┼───────────────┤
│ 0 │ ssh,tar │ tar through ssh session │ Duplicate     │
╰───┴─────────┴─────────────────────────┴───────────────╯

관련 정보