假设我们有一个a.json文件。该文件包含许多属性。例如在文件中,我只显示了两个属性“name”和“age”。实际上,还有更多具有数值的属性。
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
35,
25,
23
]
...//other attributes with numerical values
}
Run Code Online (Sandbox Code Playgroud)
我们如何转换如下文件?
{
"name":[
"James",
"Alek",
"Bob"
],
"age":[
"35",
"25",
"23"
]
...//other attributes with numerical values
}
Run Code Online (Sandbox Code Playgroud)
jq解决方案您可以使用jq的walk()内置函数递归遍历 JSON 值,检查它们的types 并转换数字tostring()。
假设您的 JSON 存储在 file 中input.json,命令如下:
jq 'walk(if type == "number" then tostring else . end)' input.json
Run Code Online (Sandbox Code Playgroud)
它将修改后的 JSON 转储到屏幕,其输出可以重定向到另一个文件 ( > output.json)。
最有可能的是,上面的命令失败并显示错误消息:
jq: error: walk/1 is not defined at <top-level>, line 1:
Run Code Online (Sandbox Code Playgroud)
这意味着walk()内置不是 (!) 内置在jq您使用的版本中。该问题已在两年前报告(issue #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
Run Code Online (Sandbox Code Playgroud)
就这样!
| 归档时间: |
|
| 查看次数: |
717 次 |
| 最近记录: |