Skip to content

Instantly share code, notes, and snippets.

@fcardinaux
Created December 28, 2011 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcardinaux/1527486 to your computer and use it in GitHub Desktop.
Save fcardinaux/1527486 to your computer and use it in GitHub Desktop.
Suggestion for Zotonic: a filter to escape strings for JSON output
%% @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]).
@fcardinaux
Copy link
Author

Here is how to use it in templates:

{{ value|escapejson }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment