public
Created

Suggestion for Zotonic: a filter to escape strings for JSON output

  • Download Gist
filter_escapejson.erl
Erlang
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
%% @author François Cardinaux, inspired by Marc Worrell's filter_escapejs module
%% and z_utils:json_escape/1 function
%% @copyright 2011 François Cardinaux
%% @doc Zotonic filter to escape strings as specified on http://www.json.org/
 
%% Copyright 2011 François Cardinaux
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
 
-module(filter_escapejson).
-export([escapejson/2]).
 
%% @doc Escape a string for JSON
escapejson(undefined, _Context) ->
<<>>;
escapejson(Input, _Context) when is_binary(Input) ->
json_escape(Input);
escapejson(Input, _Context) when is_list(Input) ->
json_escape(Input).
 
%% @todo This support function could be moved to z_utils
json_escape(undefined) -> [];
json_escape([]) -> [];
json_escape(<<>>) -> [];
json_escape(Value) when is_integer(Value) -> integer_to_list(Value);
json_escape(Value) when is_atom(Value) -> json_escape(atom_to_list(Value), []);
json_escape(Value) when is_binary(Value) -> json_escape(binary_to_list(Value), []);
json_escape(Value) -> json_escape(Value, []).
 
json_escape([], Acc) -> lists:reverse(Acc);
json_escape([$" |T], Acc) -> json_escape(T, [$" ,$\\|Acc]);
json_escape([$\\|T], Acc) -> json_escape(T, [$\\,$\\|Acc]);
json_escape([$/ |T], Acc) -> json_escape(T, [$/ ,$\\|Acc]);
json_escape([$\b|T], Acc) -> json_escape(T, [$b ,$\\|Acc]);
json_escape([$\f|T], Acc) -> json_escape(T, [$f ,$\\|Acc]);
json_escape([$\n|T], Acc) -> json_escape(T, [$n ,$\\|Acc]);
json_escape([$\r|T], Acc) -> json_escape(T, [$r ,$\\|Acc]);
json_escape([$\t|T], Acc) -> json_escape(T, [$t ,$\\|Acc]);
json_escape([H|T], Acc) when is_integer(H) ->
json_escape(T, [H|Acc]);
json_escape([H|T], Acc) ->
H1 = json_escape(H),
json_escape(T, [H1|Acc]).

Here is how to use it in templates:

{{ value|escapejson }}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.