I have something like the following

echo "{\"t\":\"set foo='{\\\"mode\\\":1}'\"}"|jq .
  "t": "set foo='{\"mode\":1}'"

and I'd like the output to look something like

  "t": "set foo='{\"mode\":1}'",
  "mode": 1

Right now I am making several execs to make this happen and would like to see if its possible into one jq call.

  • It's unclear why you can't just add the "mode": 1 bit to our echo. – Kusalananda Dec 7 '18 at 20:11
  • 1
    It sounds more like testing challenge, but it shouldn't be treated as applicable and practical example. I can present a solution, but the point is that you need to manage your input to not get into such fragile pipes – RomanPerekhrest Dec 7 '18 at 20:14
  • This is an example of a real world example. In this case there is no control over the input, for it is a complex pipe. – winmutt Dec 7 '18 at 21:06

For this exact input,

jq '. + (.t[9:-1] | fromjson)'

will do what you want. It extracts characters {"mode":1} from the string (starting at 9, omitting the last one) so that it leaves off the single quotes on both sides, then parses it as JSON into an object with fromjson, and finally merges that object ({"mode": 1}) with the original input (.) using +.

You will need to adjust the indices to match your real data. If you need to find where the opening ' is, (.t|index("\u0027")+1) will work as a replacement for 9; if you need to parse it out more thoroughly, ask a fresh question.

  • This didn't work out of the back but I'll fiddle around some. – winmutt Dec 7 '18 at 21:20
  • The comment you posted pre-edit seemed to show it working and the output is verbatim what's in the question; if it's not what you wanted, you can edit the question to say what you actually wanted – Michael Homer Dec 7 '18 at 21:29
  • You are correct, I misread the output. This ended up working fine along with some other tweaks. Thanks again! – winmutt Dec 7 '18 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.