最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jq - Round numbers anywhere in a JSON document - Stack Overflow

programmeradmin4浏览0评论

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
  }
}

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
  }
}
Share Improve this question edited 5 hours ago DarkBee 15.6k8 gold badges70 silver badges115 bronze badges asked 5 hours ago Rainer JungRainer Jung 7407 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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

发布评论

评论列表(0)

  1. 暂无评论