简体   繁体   English

使用JQ展平嵌套的Json对象

[英]Flatten nested Json objects with JQ

I am creating a script to transform JSON objects to "string" files (for translation purposes). 我正在创建一个脚本来将JSON对象转换为“字符串”文件(用于翻译目的)。 the idea is to transform: 想法是转变:

{
   "TRANSLATION1": "text1",
   "TRANSLATION2": "text2"
}

into

"TRANSLATION1" = "text1";
"TRANSLATION2" = "text2";

That was done with : jq -r 'to_entries|map("\\"\\(.key)\\"=\\(.value|tojson);")|.[]' 这完成了: jq -r 'to_entries|map("\\"\\(.key)\\"=\\(.value|tojson);")|.[]'

Nice! 太好了!

Now, my problem is with nested objects: 现在,我的问题是嵌套对象:

{
   "TRANSLATION1": "text1",
   "TRANSLATION2": "text2",
   "TRANSLATION3": {
     "SUBTRANS1": "subtranslation1",
     "SUBTRANS2": "subtranslation2",
   }
}

I would like to have as result: 我希望得到结果:

"TRANSLATION1" = "text1";
"TRANSLATION2" = "text2";
"TRANSLATION3.SUBTRANS1" = "subtranslation1";
"TRANSLATION3.SUBTRANS2" = "subtranslation2";

Can anyone help?! 有人可以帮忙吗?! I have been scratching my head for hours now... 我现在已经摸不着头几个小时了......

One approach would be to use tostream : 一种方法是使用tostream

tostream
| select(length==2)
| (.[0] | join(".")) as $k
| .[1] as $v
| "\"\($k)\" = \"\($v)\";"

When used with the -r command-line option, this will produce the desired results, assuming the input is valid JSON. 当与-r命令行选项一起使用时,假设输入是有效的JSON,这将产生所需的结果。

Checking the key assumption [*] 检查关键假设[*]

It might be worth making explicit that the output format may not be very useful if any key name contains a period, so it might be worth checking that this is indeed the case, eg as follows: 可能值得明确的是,如果任何键名包含句点,则输出格式可能不是非常有用,因此可能值得检查确实是这种情况,例如如下:

[.. | objects | keys_unsorted[]]
| map(select(index(".")))
| unique[]

If your jq does not have tostream 如果你的jq没有tostream

paths as $path
| getpath($path) 
| strings
| "\"\($path|join("."))\" = \"\(.)\";"

[*] pun intended 双关语意图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM