기존 JSON 배열의 모든 항목에 변수를 추가하려면 어떻게해야합니까?

Dec 08 2020

json 파일에서 다음 JSON 배열이 있습니다.

[
  {
    "key": "Ley1",
    "file": "Filepath1",
    "line": 10,
    "rule": "csharpsquid:S1643",
    "message": "Use a StringBuilder instead.",
    "type": "CODE_SMELL"
  },
  {
    "key": "Key2",
    "file": "FilePath2",
    "line": 12,
    "rule": "csharpsquid:S1643",
    "message": "Use a StringBuilder instead.",
    "type": "CODE_SMELL"
  }
]

bash 명령을 사용하여 모든 항목에 "critical"변수를 추가하여 다음과 같이 표시합니다.

[
      {
        "key": "Key1",
        "file": "Filepath1",
        "line": 10,
        "rule": "csharpsquid:S1643",
        "message": "Use a StringBuilder instead.",
        "type": "CODE_SMELL",
        "critical": "No"
      },
      {
        "key": "Key2",
        "file": "FilePath2",
        "line": 12,
        "rule": "csharpsquid:S1643",
        "message": "Use a StringBuilder instead.",
        "type": "CODE_SMELL",
        "critical": "Yes"
      }
    ]

불행히도 저는 완전한 JSON 및 bash 초보자이며이 문제를 해결하는 bash 명령을 찾을 수 없습니다. 나는 jq-play에서 jq로 조금 시도했지만 실제로 무언가로 이어지지 않았으므로 여기서 시도하고 싶었습니다. 나는 이것이 모든 정보가 필요하기를 바랍니다. 그래서 누구든지 이것에 대한 명령을 알고 있습니까?

편집 : 이것은 여기에서 일했습니다, 감사합니다!

.[] |= . + {"critical": "No"}

하지만 아니요 파일 값에 따라 "예"또는 "아니요"의 값을 결정하고 싶습니다. 임계 값을 결정하기 위해 파일 값을 확인하도록 명령을 편집하는 방법을 알고 있습니까?

다음과 같이 결정해야합니다.

Filepath1, Filepath3은 "critical" : "No"

Filepath2, Filepath4, Filepath5는 "critical" : "Yes"

답변

0stone0 Dec 08 2020 at 18:48

jq if 문을 사용할 수 있습니다 .

jq '.[] |= . + {"critical": (if .file == "FilePath1" or .file == "FilePath3" then "no" else "yes" end)}'

jqPlay에서 사용해보십시오

peak Dec 09 2020 at 04:08

중복성을 최소화하려면 다음을 사용할 수 있습니다.

map(. + {critical: (if .file | IN("FilePath1", "FilePath3") then "no" else "yes" end) })

또는 간결함을 위해 :

map(. + {critical: ((.file | select(IN("FilePath1", "FilePath3")) | "no") // "yes" )})