如何在jq中将JSON对象转换为key = value格式?

gia*_*bao 31 bash json jq

在jq中,如何将JSON转换为字符串key=value

从:

{
    "var": 1,
    "foo": "bar",
    "x": "test"
}
Run Code Online (Sandbox Code Playgroud)

至:

var=1
foo=bar
x=test
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 52

你可以尝试:

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

这是一个演示:

$ 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
Run Code Online (Sandbox Code Playgroud)

  • 有什么办法可以递归地做到这一点吗? (3认同)

pea*_*eak 5

有什么办法可以递归地做到这一点吗?

这是一个可以执行您想要的功能的函数:

# 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;
Run Code Online (Sandbox Code Playgroud)

示例:发出键=值对

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


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

更新:在 jq 1.5 发布后,walk/1 被添加为 jq 定义的内置函数。它可以与上面定义的 kv 一起使用,例如如下:

 walk(if type == "object" then kv else . end) 
Run Code Online (Sandbox Code Playgroud)

使用上述输入,结果将是:

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

要“展平”输出,可以使用 flatten/0。这是一个完整的例子:

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

输入:

[ {"a":1}, [[{"b":2, "c": 3}]] ]
Run Code Online (Sandbox Code Playgroud)

输出:

a=1
b=2
c=3
Run Code Online (Sandbox Code Playgroud)


slm*_*slm 5

顺便说一句,以@aioobe 的出色答案为基础。如果您需要键全部大写,您可以ascii_upcase通过修改他的示例来完成此操作:

jq -r 'to_entries|map("\(.key|ascii_upcase)=\(.value|tostring)")|.[]'
Run Code Online (Sandbox Code Playgroud)

例子

我有一个与您类似的场景,但希望在创建用于访问 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.....
Run Code Online (Sandbox Code Playgroud)

参考