使用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遍历数组元素,逐步构建最终的目标对象:- 对每个元素,判断
translation.content的类型: - 若
content是对象(如car对应的多语言内容),先用to_entries将其转为键值对数组,再遍历每个键值对,生成[term]_[key]格式的新键,赋值对应的值 - 若
content是字符串(如title对应的单条内容),直接用term作为键,将content的值赋值过去
- 对每个元素,判断
内容的提问来源于stack exchange,提问作者Michael Jensen
相关产品推荐
相关产品推荐

