[英]How to convert all integers in a json file to strings via jq command?
Suppose that we have a a.json
file. 假设我们有一个
a.json
文件。 The file contains many attributes. 该文件包含许多属性。 For example in the file, I just show two attributes "name" and "age".
例如,在文件中,我仅显示两个属性“名称”和“年龄”。 In fact there are more attributes having numerical values though.
实际上,尽管有更多具有数值的属性。
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
35,
25,
23
]
...//other attributes with numerical values
}
How can we convert the file like the following? 我们如何像下面这样转换文件?
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
"35",
"25",
"23"
]
...//other attributes with numerical values
}
jq
solution jq
解决方案 You can use the jq
's walk()
builtin to recursively walk the JSON values, check their type
s and convert the numbers tostring()
. 您可以使用
jq
的内置walk()
来递归遍历JSON值,检查其type
s并将数字转换为tostring()
。
Assuming your JSON is stored in the file input.json
, the command is like: 假设您的JSON存储在文件
input.json
,则命令类似于:
jq 'walk(if type == "number" then tostring else . end)' input.json
It dumps the modified JSON to the screen and its output can be redirector to another file ( > output.json
). 它将修改后的JSON转储到屏幕上,其输出可以重定向到另一个文件(
> output.json
)。
Most probably, the command above fails with the error message: 最有可能的是,以上命令失败并显示错误消息:
jq: error: walk/1 is not defined at <top-level>, line 1:
It means the walk()
builtin is not (!) built into the jq
version you use. 这意味着内置的
walk()
不是您所使用的jq
版本中内置的(!)。 The issue has been reported two years ago (issue #1106 ) but it apparently is not a bug but an optional feature. 该问题已在两年前报告(问题#1106 ),但显然不是错误,而是可选功能。 The definition of builtins can be downloaded from Github's project page.
内置的定义可以从Github的项目页面下载 。 Once downloaded and saved in a local file, the builtins module can be loaded using
include()
and used. 一旦下载并保存到本地文件中,内置模块就可以使用
include()
加载并使用。
Your workflow would look like this: 您的工作流程如下所示:
# 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
That's all! 就这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.