http://4096.info/2014/05/28/mochiweb%E4%B8%8Ecowboy%E4%BD%BF%E7%94%A8json/
The server's original socket implementation mechanism changed to ranch, so that you can focus on the maintenance of their own things. In fact, the reason for using ranch is because I use bigwig to monitor the status in the Web, and bigwig uses Ranch,cowboy for cowboy and ranch, so there are two HTTP frames in the code, Mochiweb and Cowboy, and looked at the structure of ranch, feel very good, will be the socket server is also converted to ranch-based architecture. Mochiweb a single module to make the HTTP service feel repetitive, it decided to remove the Mochiweb from the module and switch to Cowboy.
Everything is going well, but the data interaction between the server and the Web page is always problematic, and the data interaction uses the JSON format, mochiweb with its own method of converting Erlang data to JSON, Cowboy uses JSX, the code is
Mochijson2:encode([{success,True},{root,[]}]),jsx: Term_to_json([{success,true},{root,[]}]),
Looks very consistent, I also thought there would be no big problem, and then ran into the following format
data=[{ "ID" , 1}, {<<< span class= "str" > "name" >>< Span class= "pun" >;, <<>> }].
The Mochiweb side outputs are:
"{\" id\ ": 1,\" name\ ": \" zhangsan\ "}"
And the JSX side output is:
"[{\" _type\ ": \" tuple\ ", \" data\ ": [\" id\ ", 1]},{\" _type\ ": \" tuple\ ", \" data\ ": [\" name\ ", \" Zhangsan\ "]}]"
If you want to be consistent with the Mochiweb output, data needs to use the following method:
% Method1RecommendedData=[{≪≪"ID"≫≫, 1}, {≪≪"Name"≫≫, ≪≪"Zhangsan">>< Span class= "PLN" >}]. % method 2data2 =[{ ' ID ' , 1 }, { ' name ' , <<< span class= "str" > "Zhangsan" >& gt;}].
Obviously not the data I want, through the survey, found that JSX has the following limitations:
As the field name of the JSON index, cannot be a string list, if it is atom or binary, then the output of Mochiweb and the same, and basically with the understanding of the same, if it is a string list, then Jsx think this is an array, which may be Because Erlang does not have a real string, the string is represented in Erlang as a list.
Mochiweb and Cowboy using JSON