For as well as JSON works with make, I wish there would be a simple module to escape JSON. Sometimes you grab some text somewhere and want to fill it into some JSON somewhere else. Create JSON isn’t always an option with more dynamic structures, and in those cases, I’ve found there are options to escape JSON.
We can take some inspiration from this post: Do you know a solid way to Create JSON? - #11 by Runcorn
and use a chain of replace functions to try and escape JSON.
{{replace(replace(replace(replace(replace(replace(replace(49.`3`; "/\n/g"; space); "/\r/g"; space); "/\t/g"; space); "/\f/g"; space); "/\//g"; "/"); "/\\/g"; "\\"); "/""/g"; "\""")}}
It’s ugly, but it works decently well and doesn’t take up any extra operations.
If an extra operation isn’t much of an issue, I prefer going with a different option. The Create JSON module escapes JSON for us reliably, but it does put it inside a JSON string.
So if we create an extremely simple data structure that only consists of one string, we can fill in some data.
Data structure:
Then, we can put some text in there that needs escaping.
Run it once and the output should be something like this:
{"Escape":"She said, \"Hello, how are you?\"He replied, \"I'm good, thanks!\"Let's meet at 5:00 pm."}
Which is great! Now all we need is to be able to remove the JSON bits at the start and at the end. To achieve this, we can use a replace function:
{{replace(2.json; "/^\{""Escape"":""|""}$/g"; "")}}
The end result is some nicely escaped JSON:
This one is more reliable than the first option but does require an extra operation, so there’s something to be said for both.
I hope this helps out anyone else!