Search code examples
jsonjqrounding

Round numbers anywhere in a JSON document


I want to compare lots of JSON-Documents without caring about a precision more then 2 digits. I want to round any number in a JSON-Document, but I do not know where in the documents numbers are (but they are not keys).
I'm currently just using a regex (sed 's/\(\.[0-9][0-9]\)[0-9]*/\1/g'), but like this, 0.9999 or 1.0001 do have the same result.

I know how to do it when I know in which paths numbers are, but how do I do it, if I do not specify any location of numbers in the document?

From this source:

{
  "a": -4e-12,
  "b": {
    "c": 0.999999999999997,
    "d": 101.12222222222
  }
}

I'd expect a result like:

{
  "a": 0,
  "b": {
    "c": 1,
    "d": 101.12
  }
}

Solution

  • You can walk through the json object, and if it is a number, multiply by 100, round, and then divide by 100. This will give two decimal positions (not two significant figures). But it produces your expected output, however a = -0

    jq 'walk(if type == "number" then (.* 100 | round / 100) else . end)' data.json