2026/11/23

EEP68 erlang json module

自 erlang 27 開始,erlang 內建支援 json module,原本都是使用 jsx 套件。

資料對應 data mapping

decode

JSON erlang
Number integer() | float()
Boolean true | false
Null null
String binary()
Object #{binary() => _}

encode

Erlang JSON
integer() | float() Number
true | false Boolean
null Null
binary() String
atom() String
list() Array
#{binary() => _} Object
#{atom() => _} Object
#{integer() => _} Object

Errors

  • error(unexpected_end)

    如果 Binary 裡面包含了不完整的 JSON value

  • error({invalid_byte, Byte})

    如果 Binary 包含了錯誤的 UTF-8 byte 或是 錯誤的 byte 資料

  • error({unexpected_sequence, Bytes})

    如果 BInary 包含了錯誤的 UTF-8 escape(例如 \uXXXX 不完整)

Encode

因為 encode 是回傳 iodata() ,在列印時,用 ~ts 這個參數

1> Map = #{<<"name">> => <<"Alice">>, <<"age">> => 30}.
#{<<"age">> => 30,<<"name">> => <<"Alice">>}
2> Json = json:encode(Map).
[123,
 [[34,<<"age">>,34],58|<<"30">>],
 [[44,[34,<<"name">>,34],58,34,<<"Alice">>,34]],
 125]
3> io:format("~ts", [Json]).
{"age":30,"name":"Alice"}ok

Decode

剛剛的 Json 資料是 iodata(),在 decode 時,根據資料對應,必須要先將 iodata() 轉為 binary()。使用 iolist_to_binary() 或是 unicode:characters_to_binary()

4> Data = json:decode(unicode:characters_to_binary(Json)).
#{<<"age">> => 30,<<"name">> => <<"Alice">>}

unicode:characters_to_binary() 比較安全,除了處理 binary,還會同時轉為 UTF-8。iolist_to_binary() 會直接轉為 bytes data,速度比較快。

包裝 error,確保 decode 不會出錯

case catch json:decode(Bin) of
    {'EXIT', Reason} ->
        io:format("JSON error: ~p~n", [Reason]),
        error;
    Data ->
        Data
end.

iodata()

  • 可以是 binary
  • 或巢狀 list(裡面混 binary / byte / list)
iodata() = binary() | iolist()
iolist() = [byte() | binary() | iolist()]

stream data

假設 JSON 資料被拆成兩段

Chunk1 = <<"{\"name\":\"Ali">>.
Chunk2 = <<"ce\",\"age\":30}">>.

可以加上參數處理串流

1> Chunk1 = <<"{\"name\":\"Ali">>.
<<"{\"name\":\"Ali">>
2>     Chunk2 = <<"ce\",\"age\":30}">>.
<<"ce\",\"age\":30}">>
3>
   {continue, State} = json:decode_start(Chunk1, ok, #{}).
{continue,{<<"\"Ali">>,[],
           [<<"name">>,object,ok],
           {decode,undefined,undefined,undefined,undefined,undefined,
                   undefined,fun erlang:binary_to_float/1,
                   fun erlang:binary_to_integer/1,undefined,null},
           value}}
4> json:decode_continue(Chunk2, State).
{#{<<"age">> => 30,<<"name">> => <<"Alice">>},ok,<<>>}

References

[json — stdlib v7.3

沒有留言:

張貼留言