Skip to main content

Ruby: Weird JSON.encode Problem

Check this out:
>> ActiveSupport::JSON.decode("[1]")
=> [1]
>> ActiveSupport::JSON.decode("[1]")
=> "[1]"
Weird, right? I'm calling the same thing twice and getting a different answer each time. The second answer is clearly wrong. I should get an Array, not a String.

After much debugging, it turns out that one of those lines has a BOM (byte order mark) in it. BOMs are completely invisible. I copied it from a file that was giving me a hard time. Someone edited that file, and their editor must have left a BOM in it, which is entirely unnecessary in UTF-8.

It turns out that ActiveSupport::JSON.decode acts nonsensically if you give it a BOM. I would expect it to either ignore the BOM or crash with an exception. Instead, it gave me a nonsensical response.

Here's the bug for this issue.