PageRenderTime 26ms CodeModel.GetById 16ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

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