Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified the to_json filter to allow UTF8-encoded character strings #288

Merged
merged 4 commits into from May 7, 2012
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 36 additions & 1 deletion modules/mod_base/filters/filter_to_json.erl
Expand Up @@ -16,8 +16,43 @@
%% See the License for the specific language governing permissions and
%% limitations under the License.

%% Modified by François Cardinaux in order to convert UTF8 strings correctly
%% Usage:
%% * 8-bit character encoding (ASCII, ISO8859-x, etc.):
%% {{ value|to_json }}
%% * UTF-8 character encoding:
%% {{ value|to_json:"utf8" }}
%% * Unicode character encoding, as defined in the mochijson module:
%% {{ value|to_json:"unicode" }}

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

%% @doc Convert an Erlang list or tuple to JSON
%% @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)).

%% @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
%% * "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));

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).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that if a unknown value for encoding is given, I would rather have it fail, than to give a default encoding, which might not be at all compatible with what was requested.