Ruby To_JSON Issue with Error "Illegal/Malformed Utf-8"

Ruby to_json issue with error illegal/malformed utf-8

\xAE is not a valid character in UTF-8, you have to use \u00AE instead:

"iPhone\u00AE"
#=> "iPhone®"

Or convert it accordingly:

"iPhone\xAE".force_encoding("ISO-8859-1").encode("UTF-8")
#=> "iPhone®"

Rails rendering JSON response with UTF-8


def create
name = params[:name]
description = params[:description]
orga = params[:raidlead]
startdate = params[:startdate]
enddate = params[:enddate]

puts description

name.force_encoding("ISO-8859-1").encode("UTF-8")
description.force_encoding("ISO-8859-1").encode("UTF-8")
orga.force_encoding("ISO-8859-1").encode("UTF-8")

Did the trick, so formatting the fields before saving them in the database did the trick for me. The method that does the trick is:

string.force_encoding("ISO-8859-1").encode("UTF-8")

Thanks to Prakash Murthy for his hint.

Encoding 4 byte UTF-8 character to JSON from Rails produce invalid character

In the end, I used

JSON::dump(obj))



Related Topics



Leave a reply



Submit