sourcecode

JSON 개체를 jq의 key=value 형식으로 변환하는 방법은 무엇입니까?

codebag 2023. 3. 29. 21:28
반응형

JSON 개체를 jq의 key=value 형식으로 변환하는 방법은 무엇입니까?

jq에서 JSON을 스트링으로 변환하려면key=value?

송신원:

{
    "var": 1,
    "foo": "bar",
    "x": "test"
}

수신인:

var=1
foo=bar
x=test

다음을 시도해 보십시오.

jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' test.json

데모를 소개합니다.

$ cat test.json
{
    "var": 1,
    "foo": "bar",
    "x": "test"
}
$ jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' test.json
foo=bar
var=1
x=test

제가 이걸 반복적으로 할 수 있는 방법이 있을까요?

다음은 사용자가 원하는 기능을 수행할 수 있는 기능은 다음과 같습니다.

# Denote the input of recursively_reduce(f) by $in.
# Let f be a filter such that for any object o, (o|f) is an array.
# If $in is an object, then return $in|f;
# if $in is a scalar, then return [];
# otherwise, collect the results of applying recursively_reduce(f)
# to each item in $in.
def recursively_reduce(f):
  if type == "object" then f
  elif type == "array" then map( recursively_reduce(f) ) | add
  else []
  end;

예: import key=값 쌍

def kv: to_entries | map("\(.key)=\(.value)");


[ {"a":1}, [[{"b":2, "c": 3}]] ] | recursively_reduce(kv)
#=> ["a=1","b=2","c=3"]

업데이트: jq 1.5 출시 후 walk/1이 jq 정의 빌트인으로 추가되었습니다.위 정의된 kv와 함께 다음과 같이 사용할 수 있습니다.

 walk(if type == "object" then kv else . end) 

상기의 입력에 의해, 결과는 다음과 같습니다.

[["a=1",[["b=2",c=3"]]

출력을 "평탄화"하기 위해 플랫/0을 사용할 수 있습니다.다음으로 완전한 예를 제시하겠습니다.

jq -cr 'def kv: to_entries | map("\(.key)=\(.value)");
        walk(if type == "object" then kv else . end) | flatten[]'

입력:

[ {"a":1}, [[{"b":2, "c": 3}]] ]

출력:

a=1
b=2
c=3

덧붙여서, @aioobe의 훌륭한 답변을 바탕으로 하고 있습니다.키가 모두 대문자로 되어 있어야 하는 경우,ascii_upcase예를 들어 다음과 같이 변경합니다.

jq -r 'to_entries|map("\(.key|ascii_upcase)=\(.value|tostring)")|.[]'

저는 당신과 비슷한 시나리오를 썼지만 AWS에 접속하기 위한 환경변수를 만들 때 모든 키를 대문자로 쓰고 싶었습니다.

$ okta-credential_process arn:aws:iam::1234567890123:role/myRole | \
     jq -r 'to_entries|map("\(.key|ascii_upcase)=\(.value|tostring)")|.[]'
EXPIRATION=2019-08-30T16:46:55.307014Z
VERSION=1
SESSIONTOKEN=ABcdEFghIJ....
ACCESSKEYID=ABCDEFGHIJ.....
SECRETACCESSKEY=AbCdEfGhI.....

레퍼런스

없이.jq, 저는 json의 모든 아이템을 내보낼 수 있었습니다.grep그리고.sed단, 이것은 키/값 쌍이 있는 단순한 경우에만 유효합니다.

for keyval in $(grep -E '": [^\{]' fileName.json | sed -e 's/: /=/' -e "s/\(\,\)$//"); do
    echo "$keyval"
done

다음은 응답 예를 제시하겠습니다.

❯ for keyval in $(grep -E '": [^\{]' config.dev.json | sed -e 's/: /=/' -e "s/\(\,\)$//"); do
    echo "$keyval"       
done
"env"="dev"
"memory"=128
"role"=""
"region"="us-east-1"

언급URL : https://stackoverflow.com/questions/25378013/how-to-convert-a-json-object-to-key-value-format-in-jq

반응형