@@ -103,24 +103,42 @@ encode(Data, Config) ->
103103 end .
104104
105105jsonify (A ) when is_atom (A ) -> A ;
106- jsonify (B ) when is_binary (B ) -> B ;
106+ jsonify (B ) when is_binary (B ) ->
107+ try
108+ json :encode (B ),
109+ B
110+ catch
111+ error :{invalid_byte , _ } ->
112+ print_term_to_binary (B );
113+ error :unexpected_end ->
114+ print_term_to_binary (B )
115+ end ;
107116jsonify (I ) when is_integer (I ) -> I ;
108117jsonify (F ) when is_float (F ) -> F ;
109118jsonify (B ) when is_boolean (B ) -> B ;
110119jsonify (P ) when is_pid (P ) -> jsonify (pid_to_list (P ));
111120jsonify (P ) when is_port (P ) -> jsonify (port_to_list (P ));
112121jsonify (F ) when is_function (F ) -> jsonify (erlang :fun_to_list (F ));
113122jsonify (L ) when is_list (L ) ->
114- try list_to_binary (L ) of
115- S -> S
123+ try
124+ S = list_to_binary (L ),
125+ json :encode (S ),
126+ S
116127 catch
128+ error :{invalid_byte , _ } ->
129+ print_term_to_binary (L );
130+ error :unexpected_end ->
131+ print_term_to_binary (L );
117132 error :badarg ->
118- unicode : characters_to_binary ( io_lib : format ( " ~0p " , [ L ]) )
133+ print_term_to_binary ( L )
119134 end ;
120135jsonify ({M , F , A }) when is_atom (M ), is_atom (F ), is_integer (A ) ->
121136 <<(a2b (M ))/binary , $: , (a2b (F ))/binary , $/ , (integer_to_binary (A ))/binary >>;
122137jsonify (Any ) ->
123- unicode :characters_to_binary (io_lib :format (" ~0p " , [Any ])).
138+ print_term_to_binary (Any ).
139+
140+ print_term_to_binary (B ) ->
141+ unicode :characters_to_binary (io_lib :format (" ~0p " , [B ])).
124142
125143a2b (A ) -> atom_to_binary (A , utf8 ).
126144
@@ -340,4 +358,33 @@ newline_test() ->
340358 )
341359 ).
342360
361+ non_utf8_binary_test () ->
362+ ? assertJSONEqual (
363+ <<" {\" binary_non_utf8\" :\" <<97,98,99,128>>\" ,\" level\" :\" alert\" }" >>,
364+ iolist_to_binary (
365+ format (
366+ #{
367+ level => alert ,
368+ msg => {report , #{binary_non_utf8 => <<97 , 98 , 99 , 128 >>}},
369+ meta => #{}
370+ },
371+ #{}
372+ )
373+ )
374+ ).
375+
376+ non_utf8_list_test () ->
377+ ? assertJSONEqual (
378+ <<" {\" list\" :\" [1,2,128]\" ,\" level\" :\" alert\" }" >>,
379+ iolist_to_binary (
380+ format (
381+ #{
382+ level => alert ,
383+ msg => {report , #{list => [1 , 2 , 128 ]}},
384+ meta => #{}
385+ },
386+ #{}
387+ )
388+ )
389+ ).
343390- endif .
0 commit comments