2

I'm using Faraday gem for API connection. The body of the response from my call looks this way:

"\xEF\xBB\xBF{\r\n "uptime": "112795",\r\n "started_at": "2021-32-14 17:32:11",\r\n "version": "2.0.4",\r\n "screens": [\r\n {\r\n "index": 0,\r\n "name": "\\\\.\\DISPLAY1",\r\n "width": 2560,\r\n "height": 1342,\r\n "is_primary": true\r\n }\r\n ]\r\n}"

When I try to call .to_json on this response I get this error:

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

While the JSON.parse() give me this error:

JSON::ParserError: 809: unexpected token at '{
  "uptime": "112851",
  "started_at": "2021-32-14 17:32:11",
  "version": "2.0.4",
  "screens": [
    {
      "index": 0,
      "name": "\\\\.\\DISPLAY1",
      "width": 2560,
      "height": 1342,
      "is_primary": true
    }
  ]
}'

Is the a way to translate this response into a proper format, utilize it as a standard Ruby key-pair hash and fetch values by its keys?

PS: I'm not sure if this will be helpful but before Faraday I used HTTParty gem and responses seemed to be coded properly. This is: I didn't see this Encoding::UndefinedConversionError: error.

andrzej541
  • 919
  • 1
  • 9
  • 21
  • 1
    `\xEF\xBB\xBF` is a [UTF-8 BOM](https://en.wikipedia.org/wiki/Byte_order_mark). If Faraday doesn't remove it automatically (maybe that can be adjusted) you have to strip it manually, e.g. via `sub(/\A\xEF\xBB\xBF/, '')` – Stefan Jun 16 '21 at 07:52
  • 1
    Could also try something like `content.gsub!("\xEF\xBB\xBF".force_encoding("UTF-8"), '')` – Int'l Man Of Coding Mystery Jun 16 '21 at 14:39

0 Answers0