JSON.parse throwing Encoding :: UndefinedConversionError

Getting the following error on windows:

Encoding :: UndefinedConversionError: "\ xEF" from ASCII-8BIT to UTF-8

code:

text = File.open(file, 'r:binary', &:read); #opens file and reads it with r:binary flag
puts text; #works i get here, outputs the below file contents
data = JSON.parse(text.force_encoding(Encoding::UTF_8)); #fails here with above error

      

Note: I've tried R: UTF-8 too.


File content:

{
  "Environments": [
    {
      "Environment": "UT",
      "Configuration_Directory": "configs/",
      "Files": [
        {
          "Source": "Web.ENV.config",
          "Destination": "Web.config"
        }
      ]
    },
    {
      "Environment": "UAT",
      "Configuration_Directory": "configs/",
      "Files": [
        {
          "Source": "Web.ENV.config",
          "Destination": "Web.config"
        }
      ]
    },
    {
      "Environment": "Staging",
      "Configuration_Directory": "configs/",
      "Files": [
        {
          "Source": "Web.ENV.config",
          "Destination": "Web.config"
        }
      ]
    },
    {
      "Environment": "Production",
      "Configuration_Directory": "configs/",
      "Files": [
        {
          "Source": "Web.ENV.config",
          "Destination": "Web.config"
        }
      ]
    }
  ]
}

      

+4


source to share


1 answer


I had this problem where the original string was UTF-8 with BOM but Ruby encoded it as ASCII-8bit. I am converting a string to a byte array and then back to a string, while the encoding is in UTF-8 format.



string_value.bytes.pack("c*").force_encoding("UTF-8")

      

0


source







All Articles