cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Escape json string

ovehalseth-1
Explorer
848

I was starting on a function to replace characters that json needs to be escaped. But sybase is to clever and replaces \\n back into line break 😞

The function: ALTER FUNCTION "DBA"."JsonEnc"(IN str LONG VARCHAR ) RETURNS LONG VARCHAR DETERMINISTIC BEGIN return replace(str,char(10),'\\n') END

Test query: select 'aaa' || char(10) || 'bbb' as str, jsonenc(str) as jsonstr, replace(str,char(10),'\\n') as test

Result: str | jsonstr | test aaa aaa aaa\\nbbb bbb bbb

If the funtion replaces with say: |n it works as expected.

How do I get the function to not turn \\n back to line break.

Or is there a simpler way to escape a json string?

Accepted Solutions (0)

Answers (2)

Answers (2)

johnsmirnios
Advisor
Advisor

'\\n' is a two-character string consisting of a backslash and an n. '\\n' is identical to char(10) so replace( x, char(10), '\\n' ) does nothing.

Perhaps the difference you see in the query might have to do with the client you are using to view the result? It could be displaying a character 10 as \\n. Try using \\n in the query and see if you get a result which is (visually) the same.

ovehalseth-1
Explorer

Bah, return replace(str,char(10),'\\\\n')

Needs to escape the \\

Not sure why the replace in the query does not need to escape the \\