![](/img/trans.png)
[英]command output give object string how to convert it to json using jq
[英]How to convert all integers in a json file to strings via jq command?
假设我们有一个a.json
文件。 该文件包含许多属性。 例如,在文件中,我仅显示两个属性“名称”和“年龄”。 实际上,尽管有更多具有数值的属性。
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
35,
25,
23
]
...//other attributes with numerical values
}
我们如何像下面这样转换文件?
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
"35",
"25",
"23"
]
...//other attributes with numerical values
}
jq
解决方案 您可以使用jq
的内置walk()
来递归遍历JSON值,检查其type
s并将数字转换为tostring()
。
假设您的JSON存储在文件input.json
,则命令类似于:
jq 'walk(if type == "number" then tostring else . end)' input.json
它将修改后的JSON转储到屏幕上,其输出可以重定向到另一个文件( > output.json
)。
最有可能的是,以上命令失败并显示错误消息:
jq: error: walk/1 is not defined at <top-level>, line 1:
这意味着内置的walk()
不是您所使用的jq
版本中内置的(!)。 该问题已在两年前报告(问题#1106 ),但显然不是错误,而是可选功能。 内置的定义可以从Github的项目页面下载 。 一旦下载并保存到本地文件中,内置模块就可以使用include()
加载并使用。
您的工作流程如下所示:
# Download the builtins module (only once) and save it in './builtin.jq'
curl -O https://raw.githubusercontent.com/stedolan/jq/master/src/builtin.jq
# Process the data
jq 'include "./builtin"; walk(if type == "number" then tostring else . end)' input.json > output.json
就这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.