Skip to content

Comments

Add a strict option to Generator#519

Merged
hsbt merged 1 commit intoruby:masterfrom
Shopify:strict-dump
Dec 1, 2023
Merged

Add a strict option to Generator#519
hsbt merged 1 commit intoruby:masterfrom
Shopify:strict-dump

Conversation

@casperisfine
Copy link

The default behavior of calling to_json or even to_s on unsupported object is problematic in many cases.

>> JSON.parse(JSON.dump(Object.new))
=> "#<Object:0x00000001034d8420>"

In some cases like blind serailization into some kind of store, you may want to assert that JSON.parse(JSON.dump(obj)) == obj.

The strict option is a way to ensure this by rejecting any type that doesn't map cleanly to a JSON native type.

The default behavior of calling `to_json` or even `to_s` on unsupported
object is problematic in many cases.

```
>> JSON.parse(JSON.dump(Object.new))
=> "#<Object:0x00000001034d8420>"
```

In some cases like blind serailization into some kind of store,
you may want to assert that `JSON.parse(JSON.dump(obj)) == obj`.

The `strict` option is a way to ensure this by rejecting any type
that doesn't map cleanly to a JSON native type.
@gjtorikian
Copy link

@flori @hsbt Would it be possible to have this reviewed?

@hsbt hsbt merged commit 978ee15 into ruby:master Dec 1, 2023
@hsbt
Copy link
Member

hsbt commented Dec 1, 2023

@casperisfine Thank you. I picked your commit and fixed conflict with #525

Comment on lines +344 to +346
if state.strict?
raise GeneratorError, "#{value.class} not allowed in JSON"
elsif value.respond_to?(:to_json)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bug, see #584

casperisfine pushed a commit to casperisfine/json that referenced this pull request May 9, 2024
casperisfine pushed a commit to casperisfine/json that referenced this pull request May 9, 2024
casperisfine pushed a commit to casperisfine/json that referenced this pull request May 9, 2024
casperisfine pushed a commit to casperisfine/json that referenced this pull request May 9, 2024
hsbt pushed a commit to hsbt/ruby that referenced this pull request Oct 8, 2024
hsbt pushed a commit to ruby/ruby that referenced this pull request Oct 8, 2024
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 this pull request may close these issues.

5 participants