How to jsonencode a string containing double quotes?


#1

coding server.log(format( "\"blah\"")) server.log(http.jsonencode({"say" : format( "\"blah\"")}))

outputs"blah" { "say" : "\"blah\"" }

jsonencode doesn’t return { "say": "blah" } as I was hoping. What escape mechanism should I use to get the double quotes into the encoded string? i.e. I want to assemble a string variable and return it from a function like this
response.send(200, http.jsonencode({"say" : getWeather()}))


#2

{ “say” : " \“blah\” " }
(with 2 slashes and then the quote)


#3

You don’t need format()

server.log(http.jsonencode({ "say" : "blah" }))returns
{ "say": "blah" }

and

server.log(http.jsonencode({ "say" : "\"blah\"" }))returns
{ "say": "\"blah\"" }

If getWeather() returns a string, it should work just as you’d expect.


#4

Thanks for the tips but they’re not actually solving the issue.
{ “say” : " \“blah\” " } doesn’t get past the syntax checker so I’m not sure what mlseim is suggesting?
I’m pretty sure I need to use format to construct the string in my function because the string returned by the function is required to contain double-quote symbols, something like this:
function getQuote() { return format("\"quote\"") } server.log(getQuote()) server.log(http.jsonencode({ "say" : getQuote()}))

yields:
2017-01-07 11:06:34 UTC+0 [Agent] "quote" 2017-01-07 11:06:34 UTC+0 [Agent] { "say": "\"quote\"" }

so jsonencoding the string passed back from the function is escaping the quotes again and the http endpoint receiving this string throws an error because it is expecting { “say”: “quote” }

EDIT: I’m being very slow here. Jsonencode is doing the right thing (of course!) and escaping the quotes. Where things probably go wrong is where I handle the string at the http endpoint. This is an amazon lambda function handling a response from the imp agent, and returning a processed version of the json to the caller of the function. This involves decoding the json into a table, extracting stuff and re-encoding back into json.
Now I’ve looked at what comes out of this process, every escaped double quote becomes \\" so I should be poking about in that bit of code to find out why.


#5

I was approaching it from a PHP angle, so I guess that’s not the same here.