Format of JSON response

43 views
Skip to first unread message

Gregg Fiehler

unread,
May 3, 2016, 5:44:38 PM5/3/16
to MochiWeb
Hi, I am very new to erlang and mochiweb and am not sure how to get the correct format for a JSON response to a get call.  The response "values" of the key:value pairs when they are strings come across as ascii numbers. 

Here is a curl request to my get resource

curl --request GET http://guest:guest@localhost:15670/data/all/
{"data":{"key1":[118,97,108,117,101,49],"key2":[118,97,108,117,101,50],"key3":[104,116,116,112,58,47,47,100,111,109,97,105,110,47,116,101,115,116],"key4":123456},"data":{"key1":[118,97,108,117,101,49,98],"key2":[118,97,108,117,101,50,98],"key3":[104,116,116,112,58,47,47,100,111,109,97,105,110,47,116,101,115,116,47,98],"key4":789}}

I expect to see 

{data:[{"key1":"value1","key2":"value2","key3":"http://domain/test","key4":123456},
{"key1":"value1b","key2":"value2b","key3":"http://domain/test/b","key4":789}]}

Here is some of the erlang code
    TestDataA = [{data,[{key1,"value1"},{key2,"value2"},{key3,"http://domain/test"},{key4,123456}]},{data,[{key1,"value1b"},{key2,"value2b"},{key3,"http://domain/test/b"},  {key4,789}]}],

    Resp3 = mochijson2:encode(TestDataA),
    Req:respond({202, [{"Content-Type", "application/json"}], Json });

How do I format the Json response variable so my client receives strings for the values and not an ascii code array?

Thanks
Gregg

Bob Ippolito

unread,
May 3, 2016, 5:50:23 PM5/3/16
to moch...@googlegroups.com
In Erlang, "string" syntax is shorthand for a list of unicode codepoints (as integers). This makes it functionally indistinguishable from a list of integers. The type that you need to use to represent JSON strings with mochijson2 are UTF-8 encoded binaries. This spec is documented at the top of the module (it's easier to read if you run rebar doc and look at the HTML formatted version): https://github.com/mochi/mochiweb/blob/master/src/mochijson2.erl#L22-L56

TL;DR:

    TestDataA = [{data,[{key1,<<"value1">>},{key2,<<"value2">>},{key3,<<"http://domain/test">>},{key4,123456}]},{data,[{key1,<<"value1b">>},{key2,<<"value2b">>},{key3,<<"http://domain/test/b">>},  {key4,789}]}],

--
You received this message because you are subscribed to the Google Groups "MochiWeb" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mochiweb+u...@googlegroups.com.
To post to this group, send email to moch...@googlegroups.com.
Visit this group at https://groups.google.com/group/mochiweb.
For more options, visit https://groups.google.com/d/optout.

Gregg Fiehler

unread,
May 4, 2016, 5:49:00 PM5/4/16
to MochiWeb
Thank you!  That was exactly what I needed to know, I now have it working, just took some time to figure out how to do the conversions to this format, but finally got it, slowly learning how erlang works...
Reply all
Reply to author
Forward
0 new messages