如何通过 jq 命令将 json 文件中的所有整数转换为字符串?

use*_*424 2 json jq

假设我们有一个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)

axi*_*iac 5

一个jq解决方案

您可以使用jqwalk()内置函数递归遍历 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)

就这样!