如何用'jq'总结包含百分比的字符串字段? [英] How to sum up string fields that contain percentages with 'jq'?
问题描述
我有一个JSON文件,该文件以百分比的形式跟踪表的列宽.所以输入文件columns.json
看起来像这样:
I have a JSON file that's keeping track of column widths for a table as percentages. So the input file, columns.json
, looks something like this:
[
{
"name": "Column A",
"width": "33%"
},
{
"name": "Column B",
"width": "33%"
},
{
"name": "Column C",
"width": "33%"
},
{
"name": "Column D",
"visible": false
}
]
某些列未显示,因此没有宽度(jq '.[].width
将返回这些宽度),然后还会出现百分号.否则,我可能会使用munge | munge | paste -sd+ | bc
,这通常是我在shell中进行汇总的方法,但是在这里这似乎很愚蠢,因为jq
应该能够自己执行此操作.
Some columns are not displayed and therefore don't have widths (jq '.[].width
will return null
s for these), and then there's also the issue of the percent signs. Otherwise I might've used munge | munge | paste -sd+ | bc
, which is usually what I use for summing things up in the shell, but that seems stupid here because jq
ought to be able to do this by itself.
因此仅使用jq
,我该如何总结此文件 eg 中的width
字段,以确保它们不超过100% ?
So using only jq
, how can I sum up the width
fields from this file, e.g., to make sure they don't exceed 100%?
我在这里使用select(.)
过滤掉没有.width
的记录,然后去除百分号:
I use select(.)
here to filter out records that don't have a .width
, then get rid of the percent sign:
jq '[.[].width | select(.) | sub("%"; "")] | add' columns.json
…但这只是连接字符串并返回"333333"
.
…but that just concatenates the strings and returns "333333"
.
我没有看到"typecast"一词.在jq
手册页中,所以我认为也许会进行类型推断,在正确的上下文中将看起来像数字的字符串视为数字:
I didn't see any mention of the word "typecast" in the jq
man page, so I thought maybe it would do type inference, treating a string that looks like a number as a number in the right context:
jq '[.[].width | select(.) | sub("%"; "") | .+0] | add' columns.json
...但是这只会产生错误消息,例如:
…but that just yields and error message like:
jq: error (at columns.json:18): string ("33") and number (0) cannot be added
推荐答案
一个简短的替代方法:
map(.width[:-1] | tonumber?) | add
这篇关于如何用'jq'总结包含百分比的字符串字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!