jq技术问题:如何为字符串值添加双引号实现预期输出
解决jq输出字符串缺失双引号的问题
问题背景
给定JSON数据:
{ "stringKey": "this is a string", "numberKey": 1234, "jsonKey": [ {"numberKey": 1, "stringKey": "0x" } ] }
使用原jq表达式处理时:
to_entries|map("export let " + .key + " = " + (.value | tostring)) | .[]
得到的输出中字符串值未带双引号:
export let stringKey = this is a string export let numberKey = 1234 export let jsonKey = [{"numberKey":1,"stringKey":"0x"}]
需要实现字符串值带双引号的预期输出:
export let stringKey = "this is a string" export let numberKey = 1234 export let jsonKey = [{"numberKey":1,"stringKey":"0x"}]
解决方案
将原表达式中的tostring替换为@json过滤器,修改后的jq表达式如下:
to_entries | map("export let " + .key + " = " + (.value | @json)) | .[]
原理说明
@json会按照JSON规范序列化值:字符串类型会自动添加双引号,数字、数组、对象则保持原生的JSON格式输出,完美匹配预期需求。
内容的提问来源于stack exchange,提问作者yiksanchan
相关产品推荐
相关产品推荐

