Disable auto-converting an array of number into their corresponding characters

I have an Array of number that I want to send via AJAX. An issue is that they get converted into chars on the server by themselves.

Phoenix itself converts them.

JS:

  my_ids: Array(9) [83, 84, 85, 86, 87, 88, 89, 90, 91] // as js Array
  my_ids2: "[83,84,85,86,87,88,89,90,91]"

Server:

  params["my_ids"] => 'STUVWXYZ[',
  params["my_ids2"] => "[83,84,85,86,87,88,89,90,91]"

I’ve tried

Jason.decode(params["my_ids2"])

and the result turned out to be ‘STUVWXYZ[’ as well.

How to fix it?

Those are charlists. It’s still just a list of numbers, but the values are in a range, where they’re represented as characters:
https://hexdocs.pm/elixir/List.html#module-charlists

2 Likes

I’m not asking what they are

iex(17)> [83,84,85,86,87,88,89,90,91]
'STUVWXYZ['
iex(18)> [83,84,85,86,87,88,89,90,91] == 'STUVWXYZ['
true
iex(20)> inspect('STUVWXYZ[')
"'STUVWXYZ['"
iex(19)> inspect('STUVWXYZ[', charlists: :as_lists)
"[83, 84, 85, 86, 87, 88, 89, 90, 91]"
1 Like

It’s important to know that though. There’s no way to “disable auto-converting” as charlists and lists of numbers are actually the same. It’s how strings work in erlang. You can disable the output in e.g. iex with charlists: :as_lists as option for inspection.

But on the server I still can’t iterate over that list, the way I could if they were a list of integers

You should be. If you see a string with single-quotes it’s literally a list of numbers to the runtime.

1 Like

Please show the code that does not work…

iex(1)> 'abc' |> Enum.map(&(&1 + 1))
'bcd'
iex(2)> i v(1)
Term
  'bcd'
Data type
  List
Description
  This is a list of integers that is printed as a sequence of characters
  delimited by single quotes because all the integers in it represent valid
  ASCII characters. Conventionally, such lists of integers are referred to
  as "charlists" (more precisely, a charlist is a list of Unicode codepoints,
  and ASCII is a subset of Unicode).
Raw representation
  [98, 99, 100]
Reference modules
  List
Implemented protocols
  Collectable, Enumerable, IEx.Info, Inspect, List.Chars, String.Chars

So as you see, traversal/iteration is possible…

2 Likes

Perhaps, I overlooked something

Huh? What? Character lists are by definition a list of integers, you absolutely can iterate over them:

iex(5)> for c <- 'abcde' do
...(5)>   IO.inspect(c)
...(5)> end
97
98
99
100
101
'abcde'

There absolutely should never be a case where this is not true or something has gone horribly horribly wrong in the BEAM VM itself and it needs to be reported. What is the case where this could not be done?!