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

使用jq转换翻译JSON结构:对象数组转指定键值对

解决翻译JSON格式转换的jq脚本问题

原始输入与期望输出

原始JSON结构:

{"result": {"terms": [{"term": "title","translation": {"content": "Welcome to {{user}}"}},{"term": "car","translation": {"content": {"one": "car","other": "cars"}}}]}}

期望转换后的格式:

{"title": "Welcome to {{user}}","car_one": "car","car_other": "cars"}

jq解决方案

使用以下jq命令即可完成格式转换:

jq '.result.terms | reduce .[] as $item ({}; if $item.translation.content | type == "object" then ($item.translation.content | to_entries)[] as $entry | .["\($item.term)_\($entry.key)"] = $entry.value else .[$item.term] = $item.translation.content end)'

命令解释

  • 首先定位到目标数组:.result.terms,聚焦需要处理的核心数据
  • 通过reduce遍历数组元素,逐步构建最终的目标对象:
    1. 对每个元素,判断translation.content的类型:
    2. 若content是对象(如car对应的多语言内容),先用to_entries将其转为键值对数组,再遍历每个键值对,生成[term]_[key]格式的新键,赋值对应的值
    3. 若content是字符串(如title对应的单条内容),直接用term作为键,将content的值赋值过去

内容的提问来源于stack exchange,提问作者Michael Jensen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:36:13