1

我有一些代码可以从目录中获取文件列表,我想将其作为 json 发送回客户端

getDir('GET', [])-> 
    {ok,Sheets} = files(FileDir),
    Sheets2 = sheetJson(Sheets, ""),
    {json, [{sheets, Sheets2}]}.

sheetJson([H|T], [])->
    {File, Name, Size} = H,
    Str = [{file, File},{name, Name}],
    sheetJson(T, Str);

sheetJson([H|T], Str)->
    {File, Name, Size} = H,
    Acc = Str++[{file, File},{name, Name}],
    sheetJson(T, Acc);

sheetJson(_, Str)->Str.

此代码将返回

{"sheets":{"file":"0-Jason .csv","name":"Jason ","file":"1-State.csv","name":"State","file":"2-country.csv","name":"country"}}

但想要的东西更像

 {"sheets":{"file":"0-Jason .csv","name":"Jason "},{"file":"1-State.csv","name":"State"},{"file":"2-country.csv","name":"country"}}

如果我尝试将代码更改为任何内容,那么我会收到错误消息,例如

Unhandled Error: error:function_clause. Stacktrace: [{boss_json,json_data1,[[{sheet,{file,"0-Sheet1.csv"},{name,"Sheet1"}}],[],[]],[{file,"src/boss/boss_json.erl"},{line,31}]},{boss_json,json_data1,3,[{file,"src/boss/boss_json.erl"},{line,42}]},{boss_json,encode,2,[{file,"src/boss/boss_json.erl"},{line,16}]},{boss_web_controller_render,process_action_result,4,[{file,"src/boss/boss_web_controller_render.erl"},{line,171}]},{boss_web_controller,execute_action_inner,9,[{file,"src/boss/boss_web_controller.erl"},{line,337}]},{boss_web_controller_handle_request,process_dynamic_request,4,[{file,"src/boss/boss_web_controller_handle_request.erl"},{line,242}]},{boss_web_controller_handle_request,process_request,4,[{file,"src/boss/boss_web_controller_handle_request.erl"},{line,228}]},{boss_web_controller_handle_request,set_timer,7,[{file,"src/boss/boss_web_controller_handle_request.erl"},{line,148}]}]

编辑:我想出的解决方案

我刚刚写了一个json字符串并使用{output,_}而不是{json,_},好处是我可以在javascript错误中看到Json字符串并进行修复,与erlang一样,我只是收到一条大量消息这什么也没告诉我。

4

1 回答 1

1

您尝试生成的以下 JSON 实际上是无效的:

{"sheets":{"file":"0-Jason .csv","name":"Jason "},{"file":"1-State.csv","name":"State"},{"file":"2-country.csv","name":"country"}}

相反,您可能希望编码如下:

{"sheets":[{"file":"0-Jason .csv","name":"Jason "},{"file":"1-State.csv","name":"State"},{"file":"2-country.csv","name":"country"}]}

这将简单地通过创建工作列表来实现。基本上,您的函数getDir/2应该返回以下值:

{json, [{sheets, [
    [{file, "0-Jason .csv"}, {"name", "Jason "}],
    [{file, "1-State.csv"}, {"name", "State"}],
    [{file, "1-country.csv"}, {"name", "country"}]
]}]}.

您可能只需要更改两行:

sheetJson([H|T], [])->
    {File, Name, Size} = H,
    Str = [[{file, File},{name, Name}]],  %%% <-- here
    sheetJson(T, Str);

sheetJson([H|T], Str)->
    {File, Name, Size} = H,
    Acc = Str++[[{file, File},{name, Name}]],   %%% <-- here
    sheetJson(T, Acc);
于 2014-07-18T05:21:49.693 回答