如何使用jq将JSON文件中的字符串转换为整数? [英] How to convert a string to an integer in a JSON file using jq?
问题描述
我使用 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
Thetonumber
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屋!