Erlang编码和解码json(jsx)

时间:2019-01-22
本文章向大家介绍Erlang编码和解码json(jsx),主要包括Erlang编码和解码json(jsx)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

jsx是一个用于使用、生成和操作JSON的Erlang应用程序。灵感来源于Yajl


这里肯定有很多人好奇Yaji是什么


Yaji是一个Ruby的json框架,相当于Java的Fastjson


Github: https://github.com/happyshiyu/jsx

几个重要的方法:

  1. decode
  2. encode
  3. is_json
  4. minify
  5. 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有几个选项

  1. return_maps 返回map(jsx2.9以上版本可用)
  2. {labels, binary} 解码后的key为binary
  3. {labels, atom} 解码后的key为atom
  4. {labels, existing_atom}
    解码后的key为已存在的atom,atom不存在就会报badarg
  5. {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有几个选项

  1. {space, N} Key,逗号之后N个空格距离
    默认为0
  2. {indent, N} 换行之后N个缩进 默认为0
    默认为0
jsx2.9版本支持把map编码成JSON

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()