You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:20:35