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

  • Using the QUERY |= TRANSFORM pattern to obtain two decimal positions:

    jq '( .. | numbers ) |= ( . * 100 | round / 100 )'
    

    Or if you don't want negative zeroes,

    jq '( .. | numbers ) |= ( . * 100 | round / 100 + 0 )'