From: <wd...@fr...> - 2008-10-21 17:27:40
|
Hello steve, >> Hi all, >> >> I'm trying to return JSON data from Yaws. > >As always, it would be good to indicate which version of Yaws you're using. > >> But I got an error when I parse the result with Javascript on the client browser side. >> >> For example : >> >> The string to return is : <<"t\"est">> > >Note that that's a binary, not a string. Yes sorry for this confusion. > >> The json encoding process : json:encode({struct,[{variable,<<"t\"est">>}]}) > >Running the latest svn version of yaws under R12B-4, I get: > >Eshell V5.6.4 (abort with ^G) >1> json:encode({struct,[{variable,<<"t\"est">>}]}). >** exception exit: {json_encode,{bad_term,<<"t\"est">>}} > in function json:encode/1 > in call from lists:foldl/3 > in call from json:encode_object/1 > >If I make it a string, then it works: > >2> json:encode({struct,[{variable,"t\"est"}]}). >[123,["\"variable\"",58,"\"t\\\"est\""],125] >3> lists:flatten(json:encode({struct,[{variable,"t\"est"}]})). >"{\"variable\":\"t\\\"est\"}" > >Are you using a json module that's different from what yaws supplies? > Yes, i added a case for the encode function : "encode(B) when is_binary(B) -> encode(binary_to_list(B));" >> After json encoding we have : >> >> <<"{\"variable\":\"t\\\"est\"}">> > >That too is a binary. We actually have: > >"{\"variable\":\"t\\\"est\"}" > >> Note the "triple" \ to respect the json format > >Indeed. Note also that it's needed only because the whole thing is >within double quotes. Look what happens when you print it: > >4> io:format("~s~n", >[lists:flatten(json:encode({struct,[{variable,"t\"est"}]}))]). >{"variable":"t\"est"} > >> The yaws page : >> >> <erl> >> out(Arg) -> >> {html, json:encode({struct,[{variable,<<"t\"est">>}]})}. >> </erl> > >Or better yet: > ><erl> > out(Arg) -> > {content, "application/json", >json:encode({struct,[{variable,"t\"est"}]})}. ></erl> > >> Finally I received on the client side this string : >> >> {"variable":"t\"est"} > >which is exactly right. > >> This format do not respect the JSON standard. > >Sure it does. You are right. > >> How could I handle this case ? > >There's nothing to handle, as it's already correct: > >First, from my bash shell I create the same .yaws file as above: > >$ cat > tmp/foo.yaws ><erl> >out(Arg) -> > {content, "application/json", json:encode({struct,[{variable,"t\"est"}]})}. ></erl> > >I then run the Rhino JavaScript interpreter: > >$ rhino >Rhino 1.7 release 1 2008 03 06 >js> eval("var json = " + readUrl("http://localhost/tmp/foo.yaws")); >js> json >[object Object] >js> json.variable >t"est > >which is exactly what I'd expect to get. > Yes it works, my parser on the client side was badly used. >> Thank you for your help. > >No problem. > >--steve > Thank you. |