I am creating a script to transform JSON objects to "string" files (for translation purposes). 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);")|.[]'
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...
1 Answer 1
One approach would be to use 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.
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, e.g. as follows:
[.. | objects | keys_unsorted[]]
| map(select(index(".")))
| unique[]
If your jq does not have tostream
paths as $path
| getpath($path)
| strings
| "\"\($path|join("."))\" = \"\(.)\";"
[*] pun intended