版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38278878/article/details/86594128
jsx是一个用于使用、生成和操作JSON的Erlang应用程序。灵感来源于Yajl
这里肯定有很多人好奇Yaji是什么
Yaji是一个Ruby的json框架,相当于Java的Fastjson
Github: https://github.com/happyshiyu/jsx
几个重要的方法:
- decode
- encode
- is_json
- minify
- prettify
decode JSON解码
1> jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>).
[{<<"library">>,<<"jsx">>},{<<"awesome">>,true}]
2> jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>, [return_maps]).
#{<<"awesome">> => true,<<"library">> => <<"jsx">>}
3> jsx:decode(<<"[\"a\",\"list\",\"of\",\"words\"]">>).
[<<"a">>, <<"list">>, <<"of">>, <<"words">>]
将json转换成[{Key, Value}]
decode/1,2
decode(JSON) -> Term
decode(JSON, Opts) -> Term
JSON = json_text()
Term = json_term()
Opts = [option() | labels | {labels, Label} | return_maps]
Label = binary | atom | existing_atom | attempt_atom
Opts有几个选项
- return_maps 返回map(jsx2.9以上版本可用)
- {labels, binary} 解码后的key为binary
- {labels, atom} 解码后的key为atom
- {labels, existing_atom}
解码后的key为已存在的atom,atom不存在就会报badarg - {labels, existing_atom}
解码后的key为已存在的atom,如果atom不存在,key就会用binary
jsx2.9版本支持解码成map
encode JSON编码
1> jsx:encode([{<<"library">>,<<"jsx">>},{<<"awesome">>,true}]).
<<"{\"library\": \"jsx\", \"awesome\": true}">>
2> jsx:encode(#{<<"library">> => <<"jsx">>, <<"awesome">> => true}).
<<"{\"awesome\":true,\"library\":\"jsx\"}">>
3> jsx:encode([<<"a">>, <<"list">>, <<"of">>, <<"words">>]).
<<"[\"a\",\"list\",\"of\",\"words\"]">>
将[{Key, Value}]转换成JSON
encode/1,2
encode(Term) -> JSON
encode(Term, Opts) -> JSON
Term = json_term()
JSON = json_text()
Opts = [option() | space | {space, N} | indent | {indent, N}]
N = pos_integer()
Opts有几个选项
- {space, N} Key,逗号之后N个空格距离
默认为0 - {indent, N} 换行之后N个缩进 默认为0
默认为0
is_json 判断是否为有效的JSON
1> jsx:is_json(<<"[\"this is json\"]">>).
true
2> jsx:is_json("[\"this is not\"]").
false
3> jsx:is_term([<<"this is a term">>]).
true
4> jsx:is_term([this, is, not]).
false
minify 压缩JSON
1> jsx:minify(<<"{
\"a list\": [
1,
2,
3
]
}">>).
<<"{\"a list\":[1,2,3]}">>
prettify 美化JSON
1> jsx:prettify(<<"{\"a list\":[1,2,3]}">>).
<<"{
\"a list\": [
1,
2,
3
]
}">>
JSON与Erlang数据类型的对应关系
JSON | Erlang |
---|---|
number | integer() and float() |
string | binary() and atom() |
true, false and null | true, false and null |
array | [ ] and [JSON] |
object | #{}, [{}] and [{binary() OR atom() OR integer(), JSON}] |
see below | datetime() |