json 如何使用 jq 将数字转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35365769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use jq to convert number to string?
提问by AXE Labs
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?
如何将数字转换为字符串以便两者可以连接?
回答by AXE Labs
The jq command has the tostringfunction. It took me a while to learn to use it by trial and error. Here is how to use it:
jq 命令具有tostring功能。我花了一段时间才学会通过反复试验来使用它。以下是如何使用它:
jq -r '.[] | [ .string, .number|tostring ] | join(": ")' <<< '
[{ "number": 9, "string": "nine"},
{ "number": 4, "string": "four"}]
'
nine: 9
four: 4
回答by Andrew Neilson
An alternative and arguably more intuitive format is:
另一种可以说更直观的格式是:
jq '.[] | .string + ": " + (.number|tostring)' <<< ...
Worth noting the need for parens around .number|tostring.
值得注意的是周围需要括号.number|tostring。
回答by manatwork
For such simple case string interpolation's implicit casting to string will do it:
对于这种简单的情况字符串插值的隐式转换为字符串将做到这一点:
.[] | "\( .string ): \( .number )"
See it in action on jq?play.
在jq?play上看到它的实际效果。
回答by mniva
use 'map_values' opearator to modify objects
使用“map_values”操作符修改对象
Example
例子
{"foo": {"bar": 3}}
map_values( . + {"bar": .bar|tostring} )
{"foo": {"bar": 3}}
map_values( . + {"bar": .bar|tostring} )
Output
输出
{ "foo": { "bar": "3" } }
{ "foo": { "bar": "3" } }

