Here is my Json String
{"Timestamp":"2025-02-18T10:20:37.144Z","Values":{"Slave 1 (EL1008).Channel 1.Input":true,"Slave 1 (EL1008).Channel 2.Input":false},"MetaData":{}}
I tried the Erlang re:replace/1 function in an Erlang module below
escape_quotes(Json) -> re:replace(Json, "\"", "\\\"", [global, {return, list}]).
But when I call the function with
<moduleName>:escape_quotes({"Timestamp":"2025-02-18T10:20:37.144Z","Values":{"Slave 1 (EL1008).Channel 1.Input":true,"Slave 1 (EL1008).Channel 2.Input":false},"MetaData":{}})
I get the error
* 1:25: illegal expression
and not a json string that should look like this
{\"Timestamp\":\"2025-02-18T10:20:37.144Z\",\"Values\":{\"Slave 1 (EL1008).Channel 1.Input\":true,\"Slave 1 (EL1008).Channel 2.Input\":false},"MetaData\":{}}
Hi deceze and stackoverflow team
I created Erlang/OTP client module to communicate with emqtt. emqtt is an Erlang server for subscriptions and publications similar to publications. The server can be configure to provide subscriptions in Jason format. These subscriptions however are returned with double quotes around Key-Value pairs,e.g.,
{"Timestamp":"2025-02-18T10:20:37.144Z","Values":{"Slave 1 (EL1008).Channel 1.Input":true,"Slave 1 (EL1008).Channel 2.Input":false},"MetaData":{}}
In order to assign the json string to variable, the inner double quotes must be escaped first. Lucky I found a way of doing this in the string:replace/3. Erlang function.
handle_info({subscribe, #{topic := Topic, payload := Payload}}, State) ->
NewPayload = string:replace(Payload, "\"", "\\\"", all),
io:format("Received message on topic ~s: ~s~n", [Topic, NewPayload]),
{noreply, State};
To do this any other way you'd have to use a script like sed or awk. This approach however is not good because it has to be called from within Erlang process.The external call can slow down the Erlang process or possibly cause it to crash.