如何使用' jq'对包含百分比的字符串字段求和? [英] How to sum up string fields that contain percentages with 'jq'?

查看:49
本文介绍了如何使用' 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 将为此返回 null ),然后还有百分号的问题.否则,我可能会使用 munge |芒格|粘贴-sd + |bc ,通常是我在shell中进行汇总的方法,但这在这里似乎很愚蠢,因为 jq 应该能够自己完成此操作

Some columns are not displayed and therefore don't have widths (jq '.[].width will return nulls 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆