ruby / ruby/psych

Psych.to_json can create invalid JSON if scalar values are not marked at quoted

Open
#303 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
597
Forks
223
Avg merge
11h 23m
Merged PRs (30d)
3

Description

Steps to reproduce

I have created an executable test for this bug: https://gist.github.com/ianks/ba1f7175754780168c2a6618f13c95ec

I did not know whether to report this to Psych or Rails, just let me know if it belongs elsewhere and I will move the issue.

Expected behavior

Psych.to_json should emit valid JSON. Currently, not all keys are double-quoted; which although valid in JS, is not valid JSON.

Actual behavior

It emits invalid json, which can be seen in this example:

{"raw_attributes": {"id": null}, "attributes": {attributes: {"id": {name: "id", value_before_type_cast: null,
        type: {precision: null, scale: null, limit: null, range: {"begin": -2147483648,
            "end": 2147483648, "excl": true}}, original_attribute: null}}}, "new_record": true,
  "active_record_yaml_version": 1}
System configuration

Rails version: 5.0.0

Ruby version: 2.3.1

Notes

Upon further investigation, it seems the scalar types for attributes are not marked as quoted. Even if they are not marked as quoted, should we still quote the values since all keys need to be quoted in JSON? (corresponding code https://github.com/ruby/psych/blob/master/lib/psych/json/yaml_events.rb#L21)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with lib/psych/json/yaml_events.rb at the linked line and reproduce the issue using the executable test in the provided gist. Trace how scalar values and mapping keys are marked during Psych.to_json, then add a regression test showing that the emitted document is valid JSON with quoted keys.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
tooling
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.