0

When using quotes as part of strings one often needs to escape the quotes. I now have a string My nice title stored in \mytitle and I want to write, from LaTeX, a JSON file which reads {title: "My nice title"}. This works as in the book.

However, when the title contains a quote, such as The case "Johnny R." is cool. then I have to escape the quotes in the title, as in {title: "The case \"Johnny R.\" is cool."}.

All Javascript libraries have functions which do this automagically. But how would I do such a quote escapement from LaTeX?

6
  • 2
    using " to insert quotes in latex is wrong. It doesn't give the right quote symbols. – Ulrike Fischer Nov 16 '20 at 7:20
  • @UlrikeFischer Actually I am writing a JSON file and I need exactly a " there. I am not writing a Latex file as in "PDF". – Nobody-Knows-I-am-a-Dog Feb 1 at 19:07
  • 1
    But why don't you input the quotes directly correctly? The input of The case "Johnny R." is cool is of no use in latex as it gives the wrong quotes, and it is of no use in JSON as the encoding is wrong. – Ulrike Fischer Feb 1 at 20:21
  • @UlrikeFischer Maybe I misunderstand your "no use in latex". My document is beamer and with the fonts I use the " is perfectly fine for me although it does not produce the 66 99 scheme publishers usually require. If I move to a different documentclass, however, I realize this might, then, become a necessity, though. – Nobody-Knows-I-am-a-Dog Feb 1 at 20:37
  • 1
    that is what I mean. It is wrong in latex, and if you would use proper latex input, e.g. \enquote{Jonny R.} it would be easy to redefine it so that it writes a correct JSON to a file. – Ulrike Fischer Feb 1 at 20:41
2

If you are using LuaTeX, you can use the bundled \luaescapestring function. Otherwise, you can try the \myescapestring function implemented with LaTeX3.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{expl3}

\ExplSyntaxOn

\newcommand{\myescapestring}[1]{
  \tl_set:Nn \l_tmpa_tl {#1}
  \regex_replace_all:nnN {"} {\u{c_backslash_str}"} \l_tmpa_tl
  \tl_use:N \l_tmpa_tl
}

\ExplSyntaxOff

\begin{document}

\par\luaescapestring{this is "a string"}
\par\myescapestring{this is "a string"}

\end{document}
1
  • I get the idea but I have to write this into an external JSON file and not produce a PDF from it. If I \immediate\write the result of \myescapestring I get some unreadable gibberish in the written file. – Nobody-Knows-I-am-a-Dog Feb 1 at 19:08

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.