[英]How do I use jq to convert number to string?
Given the following jq command and Json:给定以下 jq 命令和 Json:
jq '.[]|[.string,.number]|join(": ")' <<< '
[
{
"number": 3,
"string": "threee"
},
{
"number": 7,
"string": "seven"
}
]
'
I'm trying to format the output as:我正在尝试将输出格式化为:
three: 3
seven: 7
Unfortunately, my attempt is resulting in the following error:不幸的是,我的尝试导致了以下错误:
jq: error: string and number cannot be added jq:错误:无法添加字符串和数字
How do I convert the number to string so both can be joined?如何将数字转换为字符串以便两者可以连接?
The jq command has the tostring function. jq 命令具有tostring功能。 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
.值得注意的是.number|tostring
周围需要括号。
For such simple case string interpolation 's implicit casting to string will do it:对于这种简单的情况字符串插值的隐式转换为字符串将做到这一点:
.[] | "\( .string ): \( .number )"
Given the following jq command and Json:给定以下jq命令和Json:
jq '.[]|[.string,.number]|join(": ")' <<< '
[
{
"number": 3,
"string": "threee"
},
{
"number": 7,
"string": "seven"
}
]
'
I'm trying to format the output as:我正在尝试将输出格式化为:
three: 3
seven: 7
Unfortunately, my attempt is resulting in the following error:不幸的是,我的尝试导致以下错误:
jq: error: string and number cannot be added jq:错误:无法添加字符串和数字
How do I convert the number to string so both can be joined?如何将数字转换为字符串,以便两者都可以连接?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.