-
Notifications
You must be signed in to change notification settings - Fork 6
Escaping quotes in a DataSource body attribute
User: i have a tricky js quoting/escaping problem to solve.
i am an environment called xmlui
i can do this:
<DataSource id="count" url="http://hn.jonudell.info:8081/query"
body='{ { "sql": "select count(*) as count from hn" } }'
method="POST" />
the body attribute is a string
the outer { } wraps a js expression
in this case it returns a json literal
with me so far?
Assistant: Yes, I follow so far.
User: how can i write the query
select count(*) as count from hn where title like '%Ask HN%'
Assistant: First, keep in mind that for your DSL to recognize a valid JSON literal (the { "sql": ... } part), you need double quotes for the JSON keys. Meanwhile, you’re also embedding that JSON literal in a string attribute in XML, so you have to pick an outer quoting style and then escape any conflicting quotes. A common approach is:
- Use single quotes around the entire XML attribute, so
body='...'. - Inside it, use double quotes for the JSON keys:
"sql": "...". - If the SQL itself requires single quotes (around
Ask HN), you escape them inside the JSON string.
In short, you get something like:
body='{ { "sql": "select count(*) as count from hn where title like \'%Ask HN%\'" } }'
Step by step:
- The XML attribute is
'...'. - That contains a JavaScript expression
{ { "sql": ... } }. - Inside that expression is valid JSON
"sql": "...". - Within that JSON string, single quotes around
Ask HNare escaped as\'Ask HN\'.
Hence, when the DSL processes it, you end up with a JSON object whose sql property is:
select count(*) from hn where title like 'Ask HN'
That should work cleanly in your environment.
User: this environment won't accept \'
Assistant: One workaround is to switch to an HTML/XML entity for the single quotes inside your query string. Since \' isn’t allowed in this environment, you can replace ' (around Ask HN) with ' (or '). For example:
<DataSource id="count"
url="http://hn.jonudell.info:8081/query"
body='{ { "sql": "select count(*) as count from hn where title like '%Ask HN%'" } }'
method="POST" />
Breaking it down:
- The XML attribute is single-quoted:
body='...'. - The JavaScript expression is inside curly braces:
{ { "sql": "..." } }. - We need
"sql": "..."for valid JSON property/value. - Inside that JSON string, the single quotes around
Ask HNget replaced with'(or') so that the overall attribute remains valid XML/HTML.
User: that's it!
Assistant: Great! Glad that worked out for you. Let me know if there’s anything else I can help with.