Skip to content

Commit

Permalink
Modified the to_json filter again, according to Arjan Scherpenisse's …
Browse files Browse the repository at this point in the history
  • Loading branch information
fcardinaux committed Feb 20, 2012
1 parent b7985d1 commit ea89dd8
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions modules/mod_base/filters/filter_to_json.erl
Original file line number Diff line number Diff line change
Expand Up @@ -18,41 +18,46 @@

%% Modified by François Cardinaux in order to convert UTF8 strings correctly
%% Usage:
%% * 8-bit character encoding (ASCII, ISO8859-x, etc.):
%% * If the input value contains strings of UTF-8-encoded characters:
%% {{ value|to_json }}
%% * UTF-8 character encoding:
%% {{ value|to_json:"utf8" }}
%% * Unicode character encoding, as defined in the mochijson module:
%% * If the input value contains strings of ASCII or ISO 8859-1 (= Latin-1) characters:
%% {{ value|to_json:"latin-1" }}
%% * If the input value contains strings of unicode characters, as defined in the mochijson module:
%% {{ value|to_json:"unicode" }}
%% Note that these variants only concern the strings in the input term.
%% The output will always contain utf-8-encoded strings.

-module(filter_to_json).
-export([to_json/2, to_json/3]).

%% @doc Convert an Erlang list or tuple to JSON
%% @doc Convert an Erlang list or tuple to JSON.
%% This function assumes that the input contains only strings that are composed of utf-8 characters.
%% For other encodings, use to_json/3 instead.
%% @spec to_json(ErlangTerm, Context) -> Json
%% Where:
%% * ErlangTerm = list() | tuple()
%% * Context = Zotonic context record
%% * Json = JSON content
to_json(Value, _Context) ->
mochijson:encode(z_convert:to_json(Value)).
Encoder = mochijson:encoder([{input_encoding, utf8}]),
Encoder(z_convert:to_json(Value)).

%% @doc Convert an Erlang list or tuple to JSON
%% @spec to_json(ErlangTerm, Encoding, Context) -> Json
%% Where:
%% * ErlangTerm, Context and Json: like in to_json/2
%% * Encoding =
%% * "utf8": ErlangTerm contains UTF8 strings
%% * Encoding: the character encoding of the strings in the input term (the output always contains utf-8 character strings)
%% The possible values are:
%% * "latin-1": ErlangTerm contains strings of ISO 8859-1 characters (this character set encompasses ASCII characters)
%% * "unicode": ErlangTerm contains unicode strings, as defined in the mochijson module
to_json(Value, "utf8", _Context) ->
Encoder = mochijson:encoder([{input_encoding, utf8}]),
Encoder(z_convert:to_json(Value));
%% For utf-8 input strings, use to_json/2 instead.
to_json(Value, "latin-1", _Context) ->
mochijson:encode(z_convert:to_json(Value));

to_json(Value, "unicode", _Context) ->
Encoder = mochijson:encoder([{input_encoding, unicode}]),
Encoder(z_convert:to_json(Value));

to_json(Value, _Encoding, Context) ->
to_json(Value, Context).


0 comments on commit ea89dd8

Please sign in to comment.