Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION] Jason with UTF-8 characters #141

Closed
at88mph opened this issue Sep 29, 2021 · 2 comments
Closed

[QUESTION] Jason with UTF-8 characters #141

at88mph opened this issue Sep 29, 2021 · 2 comments

Comments

@at88mph
Copy link

at88mph commented Sep 29, 2021

I have a Phoenix 1.6 app that is proxying JSON requests from a different domain. Some of the JSON coming in contains extended ASCII (French) characters:

{"name": "abcdé"}

And my controller is simply pulling it in and sending it back out again:

    def get(conn, _params) do
      url = "https://..."
      response = HTTPoison.get!(url)
      conn |> halt |> json response.body
    end

My Phoenix app is using Jason by default, but the JSON cannot be encoded on the way out:

(Jason.EncodeError) invalid byte 0xE9 in \"{\"name\": \"abcdé\"}\"

Can Jason be told to re-encode extended characters?

@michalmuskala
Copy link
Owner

michalmuskala commented Sep 30, 2021

UTF-8 is handled correctly by Jason, as JSON is defined by standards to basically work only on UTF-8 text.

Your description, however, makes it sound like the returned encoding is latin1 (judging from the 0xE9 byte, UTF-8 does not contain standalone bytes like that), which is not handled by this library (and I'd assume many other libraries).

In particular, this works just fine, when input is indeed UTF-8:

iex(1)> Jason.decode!(~S|{"name": "abcdé"}|)
%{"name" => "abcdé"}

You can always try transcoding the encoding of the string with :unicode.characters_to_binary(data, :latin1, :utf8), if you know the data is indeed in latin1.

@at88mph
Copy link
Author

at88mph commented Sep 30, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants