Create a gist now

Instantly share code, notes, and snippets.

@voluntas /jsonx.rst
Last active Dec 16, 2015

What would you like to do?
jsonx コトハジメ

jsonx コトハジメ

更新:2013-04-21
バージョン:0.0.1
作者:@voluntas
URL:http://voluntas.github.io/

概要

https://github.com/iskra/jsonx

jsonx は NIF で書かれた JSON decode/encode ライブラリです。 私の知る限り Erlang で JSON 処理する場合は一番早いです。

さらに、色々便利な機能がついています。

decode/encode

様々な形式の encode に対応しています

encode:

%% list 形式
> jsonx:encode([1, 2.3, true, false, null, atom, <<"string">>, []]).
<<"[1,2.3,true,false,null,\"atom\",\"string\",[]]">>

%% proplist 形式 (jsx)
> jsonx:encode([{name, <<"Ivan">>}, {age, 33}, {phones, [3332211, 4443322]}]).
<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>

%% struct 形式 (mochijson2)
> jsonx:encode({struct, [{name, <<"Ivan">>}, {age, 33}, {phones, [3332211, 4443322]}]}).
<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>

%% eep18 形式 (jiffy)
> jsonx:encode({[{name, <<"Ivan">>}, {age, 33}, {phones, [3332211, 4443322]}]}).
<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>

decode:

%% デフォルトは eep18 形式
> jsonx:decode(<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>).
{[{<<"name">>,<<"Ivan">>},
  {<<"age">>,33},
  {<<"phones">>,[3332211,4443322]}]}

%% eep18 形式を明示的に
> jsonx:decode(<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>, [{format, eep18}]).
{[{<<"name">>,<<"Ivan">>},
  {<<"age">>,33},
  {<<"phones">>,[3332211,4443322]}]}

%% proplist 形式
> jsonx:decode(<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>, [{format, proplist}]).
[{<<"name">>,<<"Ivan">>},
 {<<"age">>,33},
 {<<"phones">>,[3332211,4443322]}]

%% mochijson2 形式
> jsonx:decode(<<"{\"name\":\"Ivan\",\"age\":33,\"phones\":[3332211,4443322]}">>, [{format, struct}]).
{struct,[{<<"name">>,<<"Ivan">>},
         {<<"age">>,33},
         {<<"phones">>,[3332211,4443322]}]}

{} の扱い:

> jsonx:decode(<<"{}">>).
{[]}

> jsonx:decode(<<"{}">>, [{format, struct}]).
{struct,[]}

> jsonx:decode(<<"{}">>, [{format, eep18}]).
{[]}

> jsonx:decode(<<"{}">>, [{format, proplist}]).
[]

decoder/encoder

レコードから一発変換出来ます

encoder:

> F = jsonx:encoder([{person, [name, age]}, {person2, [name, phone]}]).
> F([{person,<<"IvanDurak">>,16}, {person2, <<"BabaYaga">>, 116, 6666666}]).
<<"[{\"name\": \"IvanDurak\",\"age\": 16},{\"name\": \"BabaYaga\",\"age\": 116,\"phone\": 6666666}]">>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment