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

JSON.parse Alters Encoding of Passed String Unexpectedly #529

Open
aeroastro opened this issue Jun 29, 2023 · 0 comments · May be fixed by #537
Open

JSON.parse Alters Encoding of Passed String Unexpectedly #529

aeroastro opened this issue Jun 29, 2023 · 0 comments · May be fixed by #537

Comments

@aeroastro
Copy link
Contributor

Description

I am currently developing an application where string encoding is important, and I've discovered that JSON.parse unexpectedly alters the encoding of the passed string.

Here's a simple code snippet to reproduce the issue:

require 'json'

str = '{ "hoge": "fuga" }'.force_encoding('ASCII-8BIT')

puts 'JSON'
puts "Before: #{str.encoding}"
puts JSON.parse(str)
puts "After:  #{str.encoding}"

puts

str = '{ "hoge": "fuga" }'.force_encoding('ASCII-8BIT')

puts 'JSON::Ext::Parser'
puts "Before: #{str.encoding}"
puts JSON::Ext::Parser.new(str).parse
puts "After:  #{str.encoding}"

This code yields the following output:

JSON
Before: ASCII-8BIT
{"hoge"=>"fuga"}
After:  UTF-8

JSON::Ext::Parser
Before: ASCII-8BIT
{"hoge"=>"fuga"}
After:  UTF-8

As shown above, the encoding of the string str changes from 'ASCII-8BIT' to 'UTF-8' after the JSON.parse operation.

My current environment is as follows:

$ ruby --version
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-darwin22]
$ ruby -rjson -e 'puts JSON::VERSION'
2.6.3

Expected Behavior

I would expect JSON.parse not to alter the original encoding of the passed string, unless it is necessary for the parsing operation.

Current Workaround

Currently, I'm using the dup method to create a copy of the original string before parsing it to prevent the original string's encoding from being altered:

JSON.parse(str.dup)
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

Successfully merging a pull request may close this issue.

1 participant