如何使用jq将字符串转换为JSON文件中的整数? [英] How to convert a string to an integer in a JSON file using jq?

查看:90
本文介绍了如何使用jq将字符串转换为JSON文件中的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jq将复杂的json对象转换为较小的对象。我的查询是:

I use jq to transform a complex json object into a tinier one. My query is:

jq 'to_entries[]| {companyId: (.key), companyTitle: (.value.title), companyCode: (.value.booking_service_code)}' companies.json

现在,(。key)被解析为字符串,但是我想要 companyId 是数字。

Now, the (.key) is parsed as a string, yet I want companyId to be a number.

我的当前结果如下:

{
  "companyId": "1337",
  "companyTitle": "Some company title",
  "companyCode": "oxo"
}

不过应该​​是这样的:

yet it should be like:

{
  "companyId": 1337,
  "companyTitle": "Some company title",
  "companyCode": "oxo"
}


推荐答案

jq 有内置函数,您可以将密钥通过管道传递到 tonumber

jq has inbuilt functions, you can pipe your key to tonumber:

jq 'to_entries[]| {companyId: (.key)|tonumber, companyTitle: (.value.title), companyCode: (.value.booking_service_code)}' companies.json

根据文档:


编号 tonumber 函数将其输入解析为数字。
会将格式正确的字符串转换为它们的数字等值形式,
保留数字,并在所有其他输入上给出错误。

tonumber The tonumber function parses its input as a number. It will convert correctly-formatted strings to their numeric equivalent, leave numbers alone, and give an error on all other input.

示例jq'。[] | tonumber’输入[1, 1]输出1 1

这篇关于如何使用jq将字符串转换为JSON文件中的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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