我想更新类型为";字符串";如果可能的话,将整个json转换为一个数字。如果无法将该值解析为数字,则应保留该字符串。
我用jq解决这个问题的尝试遇到了1.6版本的一个已知错误。
我不知道如何解决这个错误。有什么想法可以在不遇到这个已知错误的情况下解决任务吗?
另请参阅:更新操作符在JQ 中产生空对象
示例输入
{
"outer": {
"inner": [
{
"foo": "foo",
"bar": "11",
"count": 12,
"data": ["13", "14"]
},
{
"foo": "foo",
"bar": "15",
"count": 16,
"child": {
"otherData": ["17", "18"]
}
}
]
}
}
期望输出
{
"outer": {
"inner": [
{
"foo": "foo",
"bar": 11,
"count": 12,
"data": [13, 14]
},
{
"foo": "foo",
"bar": 15,
"count": 16,
"child": {
"otherData": [17, 18]
}
}
]
}
}
尝试1解决-不起作用
jq '(..| strings) |= try tonumber catch .'
输出
{
"outer": {
"inner": [
{
"foo": "Invalid literal at EOF at line 1, column 3 (while parsing 'foo')",
"bar": {
"__jq": 1
},
"count": 12,
"data": [
{
"__jq": 2
},
{
"__jq": 3
}
]
},
{
"foo": "Invalid literal at EOF at line 1, column 3 (while parsing 'foo')",
"bar": {
"__jq": 5
},
"count": 16,
"child": {
"otherData": [
{
"__jq": 6
},
{
"__jq": 7
}
]
}
}
]
}
}
尝试2解决-甚至更糟
jq '(..| strings) |= tonumber? // .'
输出
{
"outer": {
"inner": [
{
"count": 12,
"data": [
"14"
]
},
{
"count": 16,
"child": {
"otherData": [
"18"
]
}
}
]
}
}
按预期工作,但没有解决任务
该错误与更新运算符和try-catch表达式有关
jq '(..| strings) |= (. + "___needs_update")'
{
"outer": {
"inner": [
{
"foo": "foo___needs_update",
"bar": "11___needs_update",
"count": 12,
"data": [
"13___needs_update",
"14___needs_update"
]
},
{
"foo": "foo___needs_update",
"bar": "15___needs_update",
"count": 16,
"child": {
"otherData": [
"17___needs_update",
"18___needs_update"
]
}
}
]
}
}
这里有一个jq 1.5或更高版本的免费解决方案:
reduce paths(strings) as $p (.;
getpath($p) as $x | setpath($p; $x | tonumber? // $x))
walk
救援:
walk(if type == "string"
then . as $in | try tonumber catch $in
else . end)
或者只是:
walk(if type == "string" then tonumber? // . else . end)
增强型walk
如果您的jq没有walk
,或者您想要相对于(当前(内置版本的增强版本,请参阅jq常见问题解答(搜索def walk
(。