使用jq从CSV生成JSON时,如何将programNumber转为整数?
解决jq处理CSV时将指定字段转为整数的问题
使用jq脚本将CSV转换为JSON时,CSV中对应$input[5]的programNumber字段被识别为带引号的字符串,需要转为整数类型。
原jq脚本
jq -Rsn ' {"services": [inputs | . / "\n" | (.[] | select(length > 0) | . / ",") as $input | { "type": "mpeg2tsUdp", "sources": [ { "address": $input[1], "port": 2000, "sourceAddresses": [ $input[3] ], "programSelection": { "type": "PmtProgramNumber", "programNumber": $input[5] } }, { "address": $input[2], "port": 2000, "sourceAddresses": [ $input[4] ], "programSelection": { "type": "PmtProgramNumber", "programNumber": $input[5] } } ], "streams": [], "id": $input[0] } ], "id": "Inputs", "name": "Inputs" } ' <SourceList.csv
CSV内容
FNCHD,239.194.208.9,239.194.216.9,10.110.208.9,10.110.216.9,23 MTV,239.194.208.216,239.194.216.216,10.110.208.216,10.110.216.216,702 AEHD,239.194.208.6,239.194.216.6,10.110.208.6,10.110.216.6,1 SLATE,239.1.1.1,239.1.2.1,10.100.1.1,10.100.2.1,3
当前输出问题
生成的JSON中programNumber为字符串类型(带引号),示例片段:
{ "services": [ { "type": "mpeg2tsUdp", "sources": [ { "address": "239.194.208.9", "port": 2000, "sourceAddresses": [ "10.110.208.9" ], "programSelection": { "type": "PmtProgramNumber", "programNumber": "23" } } ], "streams": [], "id": "FNCHD" } ], "id": "Inputs", "name": "Inputs" }
修改方案
使用jq内置的tonumber函数将字符串转为整数,只需将两处programNumber: $input[5]修改为programNumber: ($input[5] | tonumber)。
修改后的完整脚本:
jq -Rsn ' {"services": [inputs | . / "\n" | (.[] | select(length > 0) | . / ",") as $input | { "type": "mpeg2tsUdp", "sources": [ { "address": $input[1], "port": 2000, "sourceAddresses": [ $input[3] ], "programSelection": { "type": "PmtProgramNumber", "programNumber": ($input[5] | tonumber) } }, { "address": $input[2], "port": 2000, "sourceAddresses": [ $input[4] ], "programSelection": { "type": "PmtProgramNumber", "programNumber": ($input[5] | tonumber) } } ], "streams": [], "id": $input[0] } ], "id": "Inputs", "name": "Inputs" } ' <SourceList.csv
正确输出
修改后programNumber变为整数类型(无引号),示例片段:
{ "services": [ { "type": "mpeg2tsUdp", "sources": [ { "address": "239.194.208.9", "port": 2000, "sourceAddresses": [ "10.110.208.9" ], "programSelection": { "type": "PmtProgramNumber", "programNumber": 23 } } ], "streams": [], "id": "FNCHD" } ], "id": "Inputs", "name": "Inputs" }
内容的提问来源于stack exchange,提问作者Martin Curran
相关产品推荐
相关产品推荐

