简体   繁体   中英

How to convert all integers in a json file to strings via jq command?

Suppose that we have a a.json file. 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
} 

A jq solution

You can use the jq 's walk() builtin to recursively walk the JSON values, check their type s and convert the numbers tostring() .

Assuming your JSON is stored in the file input.json , the command is like:

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 ).

If it fails

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. The issue has been reported two years ago (issue #1106 ) but it apparently is not a bug but an optional feature. The definition of builtins can be downloaded from Github's project page. Once downloaded and saved in a local file, the builtins module can be loaded using include() and used.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM