How to use a list with non-negative integers without making it a charlist

Hey everyone. I have to send a JSON array with non-negative integer values, for example [100, 100], as a value in a JSON payload. How can I do this without having the list changed being charlist 'dd'?

These two are exactly the same thing, just different notation. So you do not need nothing.

To explain it further, difference between [100, 100] and 'dd' is the same as between 255 and 0xff. Different notation, the same data.

4 Likes

I understand this, but the problem is I want strictly the list with integers, not a charlist, for a value in a JSON payload. The problem is that I’m constructing a JSON payload as a map and then encoding it with Poison and the value on the other end, which is a Phoenix app too, instead of it being an array [100, 100] is 'dd'.

I think the problem is actually on the receiving side. Inspecting the encoded by Poison payload seems ok, but the parameter is received with value 'dd' in the other application.

I guess I’ll have to not use a list for this, but I was wondering if there is way to still use a list with strictly integers.

1 Like

Its just representation, true = [100, 100] === 'dd'!

Enum.each('dd', &IO.inspect/1)

This will output two lines 100.

4 Likes

The point is that you cannot, because these two are exactly the same. It is just different print representation of them. Just for sake of this conversation assume that you decode JSON like this:

{"foo": 1e2}

Would you be surprised when:

IO.inspect Poison.parse!(~S[{"foo": 1e2}])

Would output:

%{"foo" => 100}

Because 1e2 == 100 in the same way [100, 100] == 'dd'. These two are exactly the same thing just textual representation is different.

2 Likes
iex(2)> 'dd' |> IO.inspect(charlists: false) 
[100, 100]

It’s just how your phoenix app is displaying it. You have a list of two 100 values.

3 Likes

To help visualize this, you can try it in IEx

iex(4)> IEx.configure([inspect: [charlists: :as_lists]])
:ok
iex(5)> [100, 100]
[100, 100]
iex(6)> IEx.configure([inspect: [charlists: :as_charlists]])
:ok
iex(7)> [100, 100]                                          
'dd'
3 Likes

Thanks for the responses everyone. :slight_smile: I had looked through the docs, but I was still a bit confused I guess.

I understand they’re essentially the same. I was confused because I wanted to take a list of integers and join them in a string with a - or :, for instance, and I thought that this might be a problem, but it is not.

Just to clarify, they are not essentially the same. The are exactly the same.

Edit

Basically, because charlists are literally a list of integers (code points), the Elixir and Erlang consoles will attempt to display all integer lists as charlists (or string for erlang). It can only do this if all values are within the ascii display range. So if you had [0, 100, 100], it would not display it as the charlist because 0 (being null) is outside of the ascii display range.

5 Likes