1

Noobie question :)

How to transform a list data structure into a string in Elixir?

Examples:

["all"]               # into "['all']"
["project", "labels"] # into "['project', 'labels']"
Nando
  • 747
  • 7
  • 23
  • Are you trying to convert a list to JSON? If not, how do you want to handle characters like `\n` or non printable ones like `"\u{0}"`? – Dogbert Jun 24 '16 at 02:34
  • Hi @Dogbert, yes, I want to convert this list to JSON format. inspect ["a", b] solved the problem. Do you think that this solution it's okay? – Nando Jun 25 '16 at 01:55

1 Answers1

2

I do not claim the only right decision but maybe this will be helpful:

iex(13)> a = ['project', 'labels']
['project', 'labels']
iex(14)> b = inspect a
"['project', 'labels']"

But for double quoted srting:

iex(21)> c = ["all"]
["all"]
iex(22)> d = inspect(c) |> String.replace("\"", "'")
"['all']"

Because "all" is a binary, but 'all' is a char_list. From here

retgoat
  • 2,414
  • 1
  • 16
  • 21
  • one should be careful with a list of numbers with this approach. For example, `inspect [7, 8]` converts the list to `"'\\a\\b'"` (i.e. the list is interpreted as a list of char codes, see the [official guide](http://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#char-lists)). To get the list as `"[7, 8]"` use an option `charlists: :as_lists` like this: `inspect [7, 8], charlists: :as_lists`. (saw this solution in [this SO answer](http://stackoverflow.com/questions/40324929/list-printed-as-string-in-elixir/40324994#40324994)) – Nil Dec 20 '16 at 16:04