user1000622
user1000622

Reputation: 529

Strip backslashes from encoded JSON response

Building a Json respose with erlang. First I construct the data in terms and then use jsx to convert it to JSON:

Response =  jsx:term_to_json(MealsListResponse),

The response actually is valid JSON according to the validators I have used:

The problem is when parsing the response in the front end. Is there a way to strip the backslashes from the Erlang side, so that the will not appear on the payload response?

Upvotes: 0

Views: 251

Answers (1)

legoscia
legoscia

Reputation: 41648

The backslashes are not actually part of the string. They're just used when the string is printed as a term - that is, in the same way you'd write it in an Erlang source file. This works in the same way as character escapes in strings in C and similar languages: inside double quotes, double quotes that should be part of the string need to be escaped with backslashes, but the backslashes don't actually make it into the string.

To print the string without character escapes, you can use the ~s directive of io:format:

io:format("~s~n", [Response]).

If you're sending the response over a TCP socket, all you need to do is converting the string to binary with an appropriate Unicode conversion. Most of the time you'll want UTF-8, which you can get with:

gen_tcp:send(MySocket, unicode:characters_to_binary(Response)).

Upvotes: 1

Related Questions