52

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

从:

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

至:

var=1
foo=bar
x=test
4

4 回答 4

87

你可以试试:

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
于 2014-08-19T07:49:10.710 回答
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;

示例:发出键=值对

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"]]]]

要“展平”输出,可以使用 flatten/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
于 2015-05-17T06:50:52.050 回答
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.....

参考

于 2019-08-30T04:51:55.940 回答
3

没有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"
于 2020-02-08T19:46:11.880 回答