ERLANG JSON

ERLANG with JSON

我 运行 遵循 erlang,

中的命令
os:cmd("curl -k -X GET http://10.210.12.154:10065/iot/get/task").

它给出了这样的 JSON 输出,

{"data":[
    {"id":1,"task":"Turn on the bulb when the temperature in greater than 28","working_condition":1,"depending_value":"Temperature","action":"123"},
    {"id":2,"task":"Trun on the second bulb when the temperature is greater than 30","working_condition":0,"depending_value":"Temperature","action":"124"}
]}

我想将此数据分类为 Id、任务、depending_value、操作。这就像将它们放入 table。我想轻松找到 Id=1 的依赖值、工作条件和操作。我该怎么做?

It gives a JSON output like this.

{"data":[{"id":1,"t ...

高度怀疑。文档说 os:cmd() returns a string,它不以 { 开头。另请注意,字符串甚至不是 erlang 数据类型,双引号是创建 list of integers 的快捷方式,而整数列表在您的情况下并不是很有用。

这里有两个选项:

  1. 在由 os:cmd() 编辑的整数列表 return 上调用 list_to_binary() 以转换为 binary.

  2. 而不是 os:cmd(),使用 erlang http 客户端,如 hackney,它将 return json 作为 binary.

你想要一个二进制文件的原因是因为你可以使用一个 erlang json 模块,比如 jsx,将二进制文件转换成一个 erlang 映射(这可能是你想要的? ).

这将是这样的:

3> Json = <<"{\"data\": [{\"x\": 1, \"y\": 2}, {\"a\": 3, \"b\": 4}] }">>. 
<<"{\"data\": [{\"x\": 1, \"y\": 2}, {\"a\": 3, \"b\": 4}] }">>

4> Map = jsx:decode(Json, [return_maps]).
#{<<"data">> =>
      [#{<<"x">> => 1,<<"y">> => 2},#{<<"a">> => 3,<<"b">> => 4}]}

5> Data = maps:get(<<"data">>, Map).     
[#{<<"x">> => 1,<<"y">> => 2},#{<<"a">> => 3,<<"b">> => 4}]

6> InnerMap1 = hd(Data).   
#{<<"x">> => 1,<<"y">> => 2}

7> maps:get(<<"x">>, InnerMap1).
1

...putting them in to a table. I want to easily find what is the depending value, working condition & action for Id=1.

Erlang 有多种 table 实现:etsdetsmnesia。这是一个 ets 示例:

-module(my).
-compile(export_all).

get_tasks() ->
    Method = get,

    %See description of this awesome website below.
    URL = <<"https://my-json-server.typicode.com/7stud/json_server/db">>,

    Headers = [],
    Payload = <<>>,
    Options = [],

    {ok, 200, _RespHeaders, ClientRef} =
        hackney:request(Method, URL, Headers, Payload, Options),
    {ok, Body} = hackney:body(ClientRef),
    %{ok, Body} = file:read_file('json/json.txt'),  %Or, for testing you can paste the json in a file (without the outer quotes), and read_file() will return a binary.

    Map = jsx:decode(Body, [return_maps]),
    _Tasks = maps:get(<<"data">>, Map).

create_table(TableName, Tuples) ->
    ets:new(TableName, [set, named_table]),
    insert(TableName, Tuples).

insert(_Table, []) ->
    ok;
insert(Table, [Tuple|Tuples]) ->
    #{<<"id">> := Id} = Tuple,
    ets:insert(Table, {Id, Tuple}),
    insert(Table, Tuples).

retrieve_task(TableName, Id) ->
    [{_Id, Task}] = ets:lookup(TableName, Id), 
    Task.

默认情况下,ets set 类型 table 确保插入的元组中的第一个位置是唯一键(或者您可以明确指定元组中的另一个位置作为唯一键) .

** 如果您有 github 帐户,我发现了一个非常酷的网站,可以让您将 json 文件放入新存储库在 github 上,网站将以 json 的形式提供该文件。在 https://my-json-server.typicode.com:

查看

How to

  1. Create a repository on GitHub (<your-username>/<your-repo>)
  2. Create a db.json file [in the repository].
  3. Visit https://my-json-server.typicode.com/<your-username>/<your-repo> to access your server

你可以看到我在代码中使用的url,可以通过点击提供的服务器页面上的link并复制url到你的代码中获得网络浏览器的地址栏。

在shell:

.../myapp$ rebar3 shell
===> Verifying dependencies...
===> Compiling myapp
src/my.erl:2: Warning: export_all flag enabled - all functions will be exported

Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [kernel-poll:false]
Eshell V9.3  (abort with ^G)

1> ===> The rebar3 shell is a development tool; to deploy applications in production, consider using releases (http://www.rebar3.org/docs/releases) 
===> Booted unicode_util_compat
===> Booted idna
===> Booted mimerl
===> Booted certifi
===> Booted ssl_verify_fun
===> Booted metrics
===> Booted hackney

1> Tasks = my:get_tasks().     
[#{<<"action">> => <<"123">>,
   <<"depending_value">> => <<"Temperature">>,<<"id">> => 1,
   <<"task">> =>
       <<"Turn on the bulb when the temperature in greater than 28">>,
   <<"working_condition">> => 1},
 #{<<"action">> => <<"124">>,
   <<"depending_value">> => <<"Temperature">>,<<"id">> => 2,
   <<"task">> =>
       <<"Trun on the second bulb when the temperature is greater than 30">>,
   <<"working_condition">> => 0}]

2> my:create_table(tasks, Tasks).
ok

3> my:retrieve_task(tasks, 1).   
#{<<"action">> => <<"123">>,
  <<"depending_value">> => <<"Temperature">>,<<"id">> => 1,
  <<"task">> =>
      <<"Turn on the bulb when the temperature in greater than 28">>,
  <<"working_condition">> => 1}

4> my:retrieve_task(tasks, 2).   
#{<<"action">> => <<"124">>,
  <<"depending_value">> => <<"Temperature">>,<<"id">> => 2,
  <<"task">> =>
      <<"Trun on the second bulb when the temperature is greater than 30">>,
  <<"working_condition">> => 0}

5> my:retrieve_task(tasks, 3).
** exception error: no match of right hand side value []
     in function  my:retrieve_task/2 (/Users/7stud/erlang_programs/old/myapp/src/my.erl, line 58)

6> 

请注意,id 在其中一行末尾的右侧。另外,如果你在shell中遇到任何错误,shell会自动重启一个新进程,etstable会被销毁,所以你必须重新创建它。

rebar.config:

{erl_opts, [debug_info]}.
{deps, [
    {jsx, "2.8.0"},
    {hackney, ".*", {git, "git://github.com/benoitc/hackney.git", {branch, "master"}}}
]}.
{shell, [{apps, [hackney]}]}. % This causes the shell to automatically start the listed apps.  See 

src/myapp.app.src:

{application, 'myapp',
 [{description, "An OTP application"},
  {vsn, "0.1.0"},
  {registered, []},
  {mod, {'myapp_app', []}},
  {applications,
   [kernel,
    stdlib
   ]},
  {env,[]},
  {modules, []},

  {contributors, []},
  {licenses, []},
  {links, []}
 ]}.

但是,根据 rebar3 dependencies docs

You should add each dependency to your app or app.src files:

所以,我想 src/myapp.app.src 应该是这样的:

{application, 'myapp',
 [{description, "An OTP application"},
  {vsn, "0.1.0"},
  {registered, []},
  {mod, {'myapp_app', []}},
  {applications,
   [kernel,
    stdlib,
    jsx,
    hackney
   ]},
  {env,[]},
  {modules, []},

  {contributors, []},
  {licenses, []},
  {links, []}
 ]}.