如何使用 jq 将数字转换为字符串?

给定以下 jq 命令和 Json:

jq '.[]|[.string,.number]|join(": ")' <<< '
[
{
"number": 3,
"string": "threee"
},
{
"number": 7,
"string": "seven"
}
]
'

我尝试将输出格式设置为:

three: 3
seven: 7

不幸的是,我的尝试导致了以下错误:

Error: 字符串和数字不能被添加

如何将数字转换为字符串以便两者都可以连接?

80994 次浏览

The jq command has the tostring function. It took me a while to learn to use it by trial and error. Here is how to use it:

jq -r '.[] | [ .string, .number|tostring ] | join(": ")' <<< '
[{ "number": 9, "string": "nine"},
{ "number": 4, "string": "four"}]
'
nine: 9
four: 4

An alternative and arguably more intuitive format is:

jq '.[] | .string + ": " + (.number|tostring)' <<< ...

Worth noting the need for parens around .number|tostring.

For such simple case string interpolation's implicit casting to string will do it:

.[] | "\( .string ): \( .number )"

See it in action on jq‣play.