我是Erlang
的新手,注意到没有从列表中创建json字符串的本地函数(或者有吗?)。我用这个方法在Erlang中创建json字符串,但不知道它是否会故障。
下面是我的方法的一个例子:
-module(index).
-export([test/0]).
test() ->
Ma = "Hello World", Mb = "Hello Erlang",
A = "{\"Messages\" : [\"" ++ Ma ++ "\", \""++Mb++"\"], \"Usernames\" : [\"Username1\", \"Username2\"]}",
A.
其结果是:
388> test().
"{\"Messages\" : [\"Hello World\", \"Hello Erlang\"], \"Usernames\" : [\"Username1\", \"Username2\"]}"
389>
我认为这是预期的结果,但当包含特殊字符时,此方法是否有可能出现故障,例如:<, >, & / \ " ?
?
我应该采取什么预防措施来使这种方法更强大?
4条答案
按热度按时间zsohkypk1#
如果
Ma
或Mb
包含双引号或任何控制字符,从字符串到JSON的解析将失败。这种解析可能永远不会在Erlang中发生,因为Erlang没有内置的字符串到JSON的转换。使用二进制文件(
<<"I am a binary string">>
)是个好主意,因为列表会消耗更多的资源。我们使用的是jiffy,它是作为NIF实现的,因此速度相当快,它允许像这样构建文档:
a2mppw5e2#
I had this very same problem, searched high and low and in the end came up with my own method. This is purely just pointing people in the right directions to finding a solution for themselves. Note: I tried jiffy but as I'm using rebar3 it's not currently compatible.
Im using MS sql server so i use the Erlang odbc module: http://erlang.org/doc/man/odbc.html
The odbc:sql_query/2 gives me back
{selected, Columns, Results}
From here i can take theColumns
which is a list of strings & the Results, a list of rows represented each as a tuple, then create a few functions to output valid Erlang code to be able to serialize correctly to Json based on a number of factors. Here's the full code:make the initial query:
Then the input function is
set_json_from_sql/3
that calls the below functions:So
set_json_from_sql/3
gives you your Json output after matchingset_json_from_sql([], [], Data)
.The key points here are that you need to call
list_to_binary/1
for strings & atoms. Usejsone
to encode Erlang objects to Json: https://github.com/sile/jsoneAnd, notice
format_by_type/1
is used to match against Erlang object types, yes not ideal but works as long as you are aware of your DB's types or you can increase the extra guards to accommodate this.omtl5h9j3#
这对我有用
输出量
或者使用github上的许多库中的一个将erlang术语转换为json.My Tuple to JSON module is simple but effective.
zsbz8rwp4#
像pro那样做