最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I escape double quotes in a json string consisting of more than one qutoed key value pair sepeated by a clon in Erlang?

programmeradmin5浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论