elixirelixir-mixelixir-poison

Escape JSON in Mix shell echo command


I have a similar code to this. I want it to echo a valid JSON with quotes on properties so that it can be piped to another command. But while echoing, it is ripping off all the quotes.

def test_function() do
  map = %{
    "key1" => 12,
    "key2" => "value1",
  }

  json = Poison.encode!(map)
  IO.inspect(json)

  Mix.Shell.cmd(
    "echo #{json}",
    fn x -> IO.puts(x) end
  )
end

Expected

{"key2":"value1","key1":12}

Actual

{key2:value1,key1:12}

Solution

  • I had to quote JSON string in single-quotes

    Mix.Shell.cmd(
      "echo '#{json}'",
      fn x -> IO.puts(x) end
    )
    

    Ref