-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.util.ex
executable file
·72 lines (53 loc) · 1.95 KB
/
json.util.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
defmodule Krug.JsonUtil do
@moduledoc """
Utilitary module to make objects (maps) can be transformated.
"""
alias Krug.StringUtil
@doc """
Transform a Map relative to a CRUD object into
a string format to be logged/stored in table log on database,
in format text similar a json string.
## Examples
```elixir
iex > map = %{echo: "ping"}
iex > Krug.JsonUtil.encode_to_log(map)
"echo: ping"
```
```elixir
iex > map = %{name: "Johannes Backend", age: 57, address: "404 street", prefer_band: "Guns Roses"}
iex > Krug.JsonUtil.encode_to_log(map)
"prefer_band: Guns Roses, name: Johannes Backend, age: 57, address: 404 street"
```
```elixir
iex > map = %{name: "Johannes Backend", age: 57, address: "404 street", prefer_band: "Guns Roses"}
iex > substitutions_array = [["prefer_band","Prefered Musical Band"],["name","Name"],["age","Age"],
["address","Actual Address"]]
iex > Krug.JsonUtil.encode_to_log(map,substitutions_array)
"Prefered Musical Band: Guns Roses, Name: Johannes Backend, Age: 57, Actual Address: 404 street"
```
"""
def encode_to_log(map,substitutions_array \\[]) do
cond do
(nil == map) -> ""
true -> encodeMap_to_log(map,substitutions_array)
end
end
defp encodeMap_to_log(map,substitutions_array) do
Poison.encode!(map)
|> StringUtil.replace(":",": ",true)
|> StringUtil.replace(",",", ",true)
|> StringUtil.replace("\"","",true)
|> StringUtil.replace("{","",true)
|> StringUtil.replace("}","",true)
|> make_substitutions(substitutions_array)
end
defp make_substitutions(json,array) do
cond do
(nil == array or Enum.empty?(array)) -> json
true -> json |> make_substitution(hd(array)) |> make_substitutions(tl(array))
end
end
defp make_substitution(json,array_element) do
json |> StringUtil.replace(array_element |> hd(),array_element |> tl() |> hd(),true)
end
end