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}

Welcome to the elixir forum.

You have to quote the Json string for echo.

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