2

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...

peak
119k21 gold badges185 silver badges218 bronze badges
asked Aug 20, 2018 at 6:13

1 Answer 1

5

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

answered Aug 20, 2018 at 6:28
Sign up to request clarification or add additional context in comments.

3 Comments

Hahaha...Glad to see some jokes on this website... I was missing it :)
thanks a lot it has been very useful. FYI, JSON objects are all well formatted, and there is no key with a '.'
Now I need to do the reverse, form "string format to JSON, with recreating the objects. I'll ping you if I don't succeed. Thanks again.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.