programing

jq를 사용하여 배열의 모든 값 가져오기

goodjava 2023. 3. 16. 21:28

jq를 사용하여 배열의 모든 값 가져오기

jq:를 사용하여 json 파일을 해석합니다.

jq .response[1].text file.json

정상적으로 동작하지만 매번 .response[2]라는 숫자를 입력해야 합니다.텍스트, .response[3]텍스트 등모든 값을 한 번에 가져오고 싶다(200개 값)

하지만 그럴 때:

jq .response[].text file.json

다음 오류가 발생함: 문자열 "text"로 번호를 인덱싱할 수 없습니다.

파일은 다음과 같습니다.

{
  "response": [
    1000,
    {
      "id": ,
      "date": ,
      "owner_id": ,
      "from_id": ,
      "post_type": "post",
      "text": "blabla",
      "attachment": {
        "type": "photo",
        "photo": {
          "pid": ,
          "aid": -7,
          "owner_id": 
        }
      },
      "attachments": [
        {
          "type": "photo",
          "photo": {
          }
        },
        {
          "type": "link",
          "link": {
            "url": "",
            "title": "",
            "description": "",
            "target": "external"
          }
        }
      ],
      "post_source": {
        "type": "vk"
      },
      "comments": {
        "count": 0,
        "groups_can_post": true,
        "can_post": 1
      },
    },
    {
      "id": ,
      "date": ,
      "owner_id": ,
      "from_id": ,
      "post_type": "post",
      "text":    "blabla",
      "attachment": {
        "type": "link",
        "link": {
          "url": "",
          "title": "",
          "description": "",
          "target": "external",
          "
        }

배열의 항목 중 하나가 문자열인 것 같습니다.jq가 「?」를 서포트하고 있는 경우는, 다음과 같이 사용할 수 있습니다.

.response[].text?

또 다른 방법은 유형을 명시적으로 확인하는 것입니다. 예를 들어 다음과 같습니다.

.response[] | objects | .text

또 다른 가능성:

.response[] | select(type=="object" and has("text")) | .text

"텍스트" 필드가 없을 때 자리 표시자 값을 지정하려면:

 .response[] | if type=="object" and has("text") then .text else null end

따라서 실제로 사용하는 jq의 버전에 따라 요구 사항이 달라집니다.

언급URL : https://stackoverflow.com/questions/45523425/getting-all-the-values-of-an-array-with-jq