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

查看:34
本文介绍了如何使用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.

我目前的结果是这样的:

My result currently looks like this:

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

但它应该是这样的:

{
  "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 函数将其输入解析为数字.它会将格式正确的字符串转换为其等效的数字,保留数字,并在所有其他输入上出错.

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天全站免登陆