@@ -18,7 +18,7 @@ defmodule RabbitMQ.CLI.Formatters.Json do
18
18
end
19
19
20
20
def format_output ( output , _opts ) do
21
- { :ok , json } = JSON . encode ( keys_to_atoms ( output ) )
21
+ { :ok , json } = JSON . encode ( keys_to_atoms ( convert_erlang_strings ( output ) ) )
22
22
json
23
23
end
24
24
@@ -72,4 +72,65 @@ defmodule RabbitMQ.CLI.Formatters.Json do
72
72
end
73
73
74
74
def machine_readable? , do: true
75
+
76
+ # Convert Erlang strings (lists of integers) to binaries for proper JSON encoding
77
+ # Also convert other Erlang-specific terms to readable strings
78
+ defp convert_erlang_strings ( data ) when is_function ( data ) do
79
+ "Fun()"
80
+ end
81
+
82
+ defp convert_erlang_strings ( data ) when is_pid ( data ) do
83
+ "Pid(#{ inspect ( data ) } )"
84
+ end
85
+
86
+ defp convert_erlang_strings ( data ) when is_port ( data ) do
87
+ "Port(#{ inspect ( data ) } )"
88
+ end
89
+
90
+ defp convert_erlang_strings ( data ) when is_reference ( data ) do
91
+ "Ref(#{ inspect ( data ) } )"
92
+ end
93
+
94
+ defp convert_erlang_strings ( data ) when is_list ( data ) do
95
+ # Only attempt Unicode conversion on proper lists of integers
96
+ if is_proper_list_of_integers? ( data ) do
97
+ case :unicode . characters_to_binary ( data , :utf8 ) do
98
+ binary when is_binary ( binary ) ->
99
+ # Successfully converted - it was a valid Unicode string
100
+ binary
101
+ _ ->
102
+ # Conversion failed - not a Unicode string, process as regular list
103
+ Enum . map ( data , & convert_erlang_strings / 1 )
104
+ end
105
+ else
106
+ # Not a proper list of integers, process as regular list
107
+ Enum . map ( data , & convert_erlang_strings / 1 )
108
+ end
109
+ end
110
+
111
+ defp convert_erlang_strings ( data ) when is_tuple ( data ) do
112
+ data
113
+ |> Tuple . to_list ( )
114
+ |> Enum . map ( & convert_erlang_strings / 1 )
115
+ |> List . to_tuple ( )
116
+ end
117
+
118
+ defp convert_erlang_strings ( data ) when is_map ( data ) do
119
+ Enum . into ( data , % { } , fn { k , v } ->
120
+ { convert_erlang_strings ( k ) , convert_erlang_strings ( v ) }
121
+ end )
122
+ end
123
+
124
+ defp convert_erlang_strings ( data ) , do: data
125
+
126
+ # Check if data is a proper list containing only integers
127
+ defp is_proper_list_of_integers? ( [ ] ) , do: false # Empty lists are not strings
128
+ defp is_proper_list_of_integers? ( data ) when is_list ( data ) do
129
+ try do
130
+ Enum . all? ( data , & is_integer / 1 )
131
+ rescue
132
+ _ -> false # Not a proper list or contains non-integers
133
+ end
134
+ end
135
+ defp is_proper_list_of_integers? ( _ ) , do: false
75
136
end
0 commit comments