/modules/mod_base/filters/filter_to_json.erl

http://github.com/zotonic/zotonic · Erlang · 49 lines · 9 code · 7 blank · 33 comment · 0 complexity · 509fbafff8aae27a2b94446ed345223a MD5 · raw file

  1. %% @author Arjan Scherpenisse <arjan@scherpenisse.net>
  2. %% @copyright 2011 Arjan Scherpenisse
  3. %% @doc Convert a value to json
  4. %% Copyright 2011 Arjan Scherpenisse
  5. %%
  6. %% Licensed under the Apache License, Version 2.0 (the "License");
  7. %% you may not use this file except in compliance with the License.
  8. %% You may obtain a copy of the License at
  9. %%
  10. %% http://www.apache.org/licenses/LICENSE-2.0
  11. %%
  12. %% Unless required by applicable law or agreed to in writing, software
  13. %% distributed under the License is distributed on an "AS IS" BASIS,
  14. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. %% See the License for the specific language governing permissions and
  16. %% limitations under the License.
  17. %% Modified by Franรงois Cardinaux in order to convert UTF8 strings correctly.
  18. %% Usage:
  19. %% * If the input value contains strings of UTF-8-encoded characters:
  20. %% {{ value|to_json }}
  21. %% or
  22. %% {{ value|to_json:"utf-8" }}
  23. %% * If the input value contains strings of ISO 8859-1 (= Latin-1) characters:
  24. %% {{ value|to_json:"latin-1" }}
  25. %% Note that these variants only concern the strings in the input term.
  26. %% The output will always contain utf-8-encoded strings.
  27. -module(filter_to_json).
  28. -export([to_json/2, to_json/3]).
  29. %% @doc Convert an Erlang list or tuple to JSON
  30. %% This function assumes that all strings of the input term are made of utf-8-encoded characters.
  31. %% @spec to_json(list() | tuple(), #context{}) -> iodata()
  32. to_json(Value, Context) ->
  33. to_json(Value, "utf-8", Context).
  34. %% @doc Convert an Erlang list or tuple to JSON
  35. %% This function assumes that the all strings of the input term have the same
  36. %% character encoding. This encoding may be UTF-8 or ISO 8859-1 (also called Latin-1).
  37. %% @spec to_json(list() | tuple(), string(), #context{}) -> iodata()
  38. to_json(Value, "latin-1", _Context) ->
  39. mochijson:encode(z_convert:to_json(Value));
  40. to_json(Value, "utf-8", _Context) ->
  41. Encoder = mochijson:encoder([{input_encoding, utf8}]),
  42. Encoder(z_convert:to_json(Value)).