JSON5 for Ruby: Gems, Parsing and Rails Config

Read JSON5 from Ruby, pick a gem that actually works, and keep it safe inside a Rails app.

Ruby's standard JSON library does not read JSON5, so you need a gem. Five turn up on RubyGems.org: two real parsers, one lenient multi-format reader, one abandoned 2014 port whose Unicode escapes and NaN handling are broken, and one empty placeholder.

This guide reads each gem's source, shows the API and the errors it raises, compares what the tests cover, and explains why no gem writes JSON5. Ruby was not available to run code here, so every claim is checked against source, not executed.

A workshop bench where JSON5 config cards are cut into Ruby hashes by a gem-cutting tool under a warm lamp

TL;DR: Use rb_json5 (RbJSON5.parse, runs on Ruby 2.4 and later) or json5-ruby (JSON5.parse, Ruby 3.2 and later, with input limits and line and column errors). Neither writes JSON5; write JSON with the standard library, which is valid JSON5. Do not install the gem named json5: it has the most downloads and is broken for Unicode escapes and NaN.

Ruby logo

Which Gem?

Searching RubyGems.org for JSON5 on November 29, 2026 returned five gems that matter. Versions, release dates, Ruby requirements and runtime dependencies below come from the RubyGems API on that day; the behavior notes come from downloading each gem and reading its source.

Gem Version Released Ruby Runtime dependency Total downloads Pick it when
rb_json5 0.3.1 11-28-2025 2.4 or later parslet ~> 2.0 147,958 You need an older Ruby, or a small API (RbJSON5.parse) built on a grammar
json5-ruby 0.1.0 08-12-2026 3.2 or later None 1,450 Input may be untrusted or large (it has limits), you want line and column errors, or a tool must keep comments
smarter_json 1.2.6 07-03-2026 2.6 or later bigdecimal 55,923 Messy human or LLM-written JSON and NDJSON; never as a validator
json5 0.0.1 03-05-2014 Not declared None 2,142,271 Never
json5rb 0.0.1 03-09-2020 Not declared None 2,809 Never

rb_json5

A JSON5 parser written with the Parslet PEG library. It reads strings and IO objects and returns plain Ruby hashes, arrays, strings, integers and floats. The gem has not had a release since 0.3.1 in November 2025; the repository's newest commits are dependency bumps for its linter, so it looks finished rather than abandoned. MIT license.

json5-ruby

A pure Ruby parser for the JSON5 1.0.0 specification, generated from a grammar file, with no runtime dependencies. It is the only gem here with configurable limits, structured errors and a comment-preserving document model. It is new (one release, August 2026) and has few downloads. The repository link in the gem's metadata returned 404 from the GitHub API when checked, so judge it by the source it ships.

smarter_json

A lenient reader for the whole family of human-written JSON: JSON5, HJSON-style config, comments, trailing commas, markdown-fenced output, JSON Lines and NDJSON. It has a C extension with a pure Ruby fallback. Leniency is the point, so it accepts input that is not JSON5. MIT license.

json5 and json5rb

The gem named json5 is a 2014 transliteration of a JavaScript parser that was never finished (details in Pitfalls). json5rb ships an empty Json5rb module and a version constant: no parser. Its RubyGems description is the literal text "[description]".

The wider field, with other languages, is on the implementations page. If you already know the Python ecosystem, the same shape (one pure-language parser, one fast one, one that preserves comments) is on the Python guide.

Download icon

Install

Bundler

# Gemfile: pick ONE of these, not both gem "rb_json5" # or, on Ruby 3.2+. The gem name differs from the file you require, # so tell Bundler which file to load: gem "json5-ruby", require: "json5"

Without Bundler

gem install rb_json5 gem install json5-ruby

Never put json5-ruby and the old json5 gem in the same bundle. Both ship lib/json5.rb and both define a top-level JSON5 module, so whichever loads first wins and the other's API silently disappears. rb_json5 uses RbJSON5 and does not collide with either.

rb_json5 pulls in parslet 2.0.0, which has not had a release since February 2020. It is a stable parser-combinator library, but it is one more dependency to track in a security scan. json5-ruby lists no runtime dependencies; its parser generator is a development-only tool.

Ruby logo

Parse JSON5 Strings and Files

How these samples were checked: not by running them. Each result in a comment is what the gem's source specifies for that input, or what its README documents. Run them once in your own Ruby before relying on them.

rb_json5

RbJSON5.parse takes a string, or any object that responds to read. Object keys are strings unless you ask for symbols.

require "rb_json5" text = <<~'CONFIG' { // service settings name: 'billing', port: 0x1F90, ratio: .75, retries: +3, tags: ['eu', 'prod',], } CONFIG config = RbJSON5.parse(text) config["name"] # => "billing" config["port"] # => 8080 config["ratio"] # => 0.75 config["retries"] # => 3 config["tags"] # => ["eu", "prod"] # symbols instead of strings RbJSON5.parse(text, symbolize_names: true)[:port] # => 8080 # from a file path, or from an open IO settings = RbJSON5.load_file("config/settings.json5", symbolize_names: true) File.open("config/settings.json5", "r:UTF-8") { |io| RbJSON5.parse(io) }

json5-ruby

JSON5.parse takes a string and keyword options. The first result below is the one its README documents.

require "json5" JSON5.parse("{ unquoted: 'value', hex: 0x2a, values: [true, null,], }") # => {"unquoted"=>"value", "hex"=>42, "values"=>[true, nil]} JSON5.valid?("{ a: 1, }") # => true JSON5.valid?("{ a: 1 ") # => false (valid? rescues JSON5::Error) # reject duplicate keys, freeze the result, name the file for error messages path = "config/settings.json5" File.open(path, "r:UTF-8") do |io| JSON5.load(io, duplicate_keys: :error, freeze: true, filename: path) end

smarter_json

SmarterJSON.process always returns an Array of documents, because it reads multi-document input such as NDJSON in one call. For a single config file use process_one. It also accepts an object with no braces, which is not JSON5.

require "smarter_json" SmarterJSON.process_one("{ name: 'billing', port: 8080, }") # a Hash with name and port SmarterJSON.process_one("host: localhost\nport: 5432") # => {"host"=>"localhost", "port"=>5432} (documented in its README) SmarterJSON.process_file("config/settings.json5", symbolize_keys: true) # an Array holding one Hash
Code icon

API Reference From Source

These signatures are copied from the released gems (rb_json5 0.3.1, json5-ruby 0.1.0, smarter_json 1.2.6), not from memory.

RbJSON5.parse(string_or_io, symbolize_names: false)

Parses a string or any object that responds to read. Returns the Ruby value: Hash, Array, String, Integer, Float, true, false or nil. Raises RbJSON5::ParseError.

RbJSON5.load_file(filename, symbolize_names: false)

Opens the file in text mode and calls parse on it. There is no option for the file's encoding, so open the file yourself when it is not in your default external encoding.

JSON5.parse(source, **options) / JSON5.load(io, **options) / JSON5.valid?(source, **options) / JSON5.parse_document(source, **options)

parse returns Ruby values, load reads an IO under the same input limit, valid? returns true or false, and parse_document returns a document model that keeps raw text, byte spans and the comments and whitespace around every node. An unknown option raises ArgumentError. The table below applies to parse, load and valid?; parse_document accepts only diagnostics, limits, filename, preserve_trivia and borrow_source.

OptionValues (default first)Effect
duplicate_keys:last, :first, :error, :preserveWhat to do with a repeated key. :preserve returns a JSON5::ObjectValue that keeps every member.
number_mode:native, :float, :lexemeIntegers stay Integer by default; :float forces Float; :lexeme returns a JSON5::NumberValue with the raw text.
string_mode:ruby, :code_units:code_units returns exact UTF-16 code units as JSON5::ECMAString.
lone_surrogate:error, :replaceWhether an unpaired surrogate escape raises or becomes U+FFFD.
diagnosticsnil, an Array, a callable, :ignoreWhere non-fatal warnings go. nil sends them to Warning.warn.
limitsJSON5::Limits.defaultSee the table below. Limits.unbounded turns every limit off.
filenamenilCopied into errors.
freezefalseFreeze the returned structure.
warn_duplicate_keysfalseEmit a duplicate_key diagnostic when the :last or :first policy drops a value.

json5-ruby default limits

LimitDefault
max_input_bytes64 MiB
max_depth512 nesting levels
max_string_code_units16 Mi UTF-16 code units
max_number_bytes1 MiB per number token
max_comment_bytes16 MiB
max_container_entries10,000,000 per array or object

SmarterJSON.process / process_one / process_file / foreach / generate

Read options (all validated; a typo raises ArgumentError): acceleration, decimal_precision (:auto, :float, :bigdecimal), duplicate_key (:last_wins, :first_wins), encoding, on_warning, replace_char, symbolize_keys. Streaming a large file is SmarterJSON.foreach(path), which returns an Enumerator that reads one document at a time. on_warning receives a SmarterJSON::Warning for every fix it applied, such as a collapsed empty comma slot, a repeated key or a number too large for Float.

For line-delimited data and the reasoning behind it, see JSON5 versus JSON Lines, and JSONL.rest, our sister reference site for JSON Lines and NDJSON.com, our sister reference site for NDJSON.

Edit icon

Writing: No Gem Emits JSON5

Of the five gems, none has a working JSON5 generator. rb_json5 and json5-ruby only parse. smarter_json has SmarterJSON.generate, but its documentation is explicit that the output is "always valid, strict JSON" (the one opt-in exception is allow_nan: true, below). The 2014 json5 gem has a stringify file, but see the pitfalls below.

That is less of a gap than it sounds, because every JSON document is already a JSON5 document. Generate JSON with the standard library and any JSON5 reader accepts it:

require "json" File.write("config/generated.json5", JSON.pretty_generate(settings)) # valid JSON5, but plain JSON: quoted keys, no comments, no trailing commas # smarter_json can emit the NaN and Infinity barewords that JSON5 allows SmarterJSON.generate({ "ratio" => Float::INFINITY }, allow_nan: true)

What you cannot do from Ruby is load a hand-written file, change one value and save it with its comments intact. Only json5-ruby's parse_document retains comments and whitespace, and it has no writer that edits a document and serializes it back. To edit a commented file today, change the text itself (for example by byte span from the document model) or use a tool from another language, as in the command-line guide.

When the standard library is enough

The json gem reached 3.0.0 on September 7, 2026 and 3.2.0 on November 24, 2026. Since 3.0 it rejects comments and duplicate keys by default, and it never accepted trailing commas, NaN or Infinity unless asked. Each of those has an option, so a file that is JSON plus comments and trailing commas (a JSONC file) needs no extra gem:

JSON.parse(text, allow_comments: true, allow_trailing_comma: true, allow_nan: true)

I found no option in the changelog or the reference for single-quoted strings, unquoted keys, hexadecimal numbers or line continuations, so a real JSON5 file still needs a gem. The trade-offs between JSON5 and a JSON-with-comments format are on the JSONC comparison.

Ruby logo

Rails Configuration, Safely

Rails' own loader for whole configuration files is Rails::Application.config_for. The Rails configuration guide documents it with .yml files under config/, keyed by environment, plus a shared key that is merged into each environment. It does not mention any other file format, so config_for(:settings) will not read a .json5 file. Parse the file yourself, once, at boot:

# config/initializers/settings.rb require "rb_json5" path = Rails.root.join("config", "settings.json5") all = RbJSON5.load_file(path.to_s, symbolize_names: true) # same idea as config_for: a shared block merged under the current environment Rails.application.config.x.settings = all.fetch(:shared, {}).deep_merge(all.fetch(Rails.env.to_sym, {})).freeze

The matching file keeps what a YAML file cannot: comments on a line you will not understand in six months.

// config/settings.json5 { shared: { // requests per minute before we answer 429 rateLimit: 600, }, development: { host: 'localhost', port: 3000, }, production: { host: 'app.example.com', port: 443, rateLimit: 1200, }, }

Read it anywhere with Rails.configuration.x.settings[:rateLimit]. config.x is the guide's documented home for custom nested configuration.

Rules that keep it safe

  • Parse at boot, not per request. rb_json5 builds a Parslet parse tree and then transforms it, which is more work than a hand-written scanner. I did not benchmark it, so measure before using it in a request loop.
  • Only parse files you ship. rb_json5 documents no input size or depth limit. For anything a user can upload or an API can return, use json5-ruby and keep its default limits, or lower them with JSON5::Limits.new(max_input_bytes: 1_000_000). See the security tutorial.
  • Keep secrets out of the file. A committed config file is for settings. Credentials belong in your secret store.
  • Fail the build on a bad file. A typo in a config file should break CI, not production. The test below covers every file.
  • Pick one gem per app. Mixing parsers makes the same file mean different things in different places.

Test every file in CI

# test/config_files_test.rb require "test_helper" class ConfigFilesTest < ActiveSupport::TestCase FILES = Dir[Rails.root.join("config", "**", "*.json5").to_s] test "config files exist" do assert_not_empty FILES, "no .json5 files found under config/" end FILES.each do |file| test "#{file} parses to an object" do assert_kind_of Hash, RbJSON5.load_file(file) end end end

The first test matters: with no files, the loop defines no tests at all, and a moved folder would silently turn the check off. The same pattern for other stacks is in schema validation and the Python guide.

Bug icon

Error Handling

Each gem raises its own error family, and none of them raise JSON::ParserError, so a rescue JSON::ParserError copied from JSON code catches nothing.

GemError classSuperclassWhat it carries
rb_json5RbJSON5::ParseErrorParslet::ParseFailed, a StandardErrorA message and parse_failure_cause (a Parslet::Cause)
json5-rubyJSON5::ParseError, LexError, EncodingError, DepthError, LimitError, ConversionError, plus DuplicateKeyError (a subclass of ParseError)JSON5::Error, a StandardErrorcode, filename, line, column, byte_offset, unexpected, expected, excerpt, and to_h
smarter_jsonSmarterJSON::ParseError, EncodingError, GenerateErrorSmarterJSON::Errorline and col on parse errors
json5 (2014)Ruby's built-in SyntaxErrorScriptError, not a StandardErrorA message with the character index

rb_json5

begin config = RbJSON5.load_file(path) rescue RbJSON5::ParseError => e warn "#{path} is not valid JSON5: #{e.message}" raise end

json5-ruby

Position information makes a good startup message. Catch JSON5::LimitError and JSON5::DepthError separately if the input is not yours, because they mean "too big", not "malformed".

begin config = JSON5.parse(File.read(path, encoding: "UTF-8"), filename: path) rescue JSON5::LimitError, JSON5::DepthError => e abort "#{path} exceeds a safety limit (#{e.code})" rescue JSON5::Error => e abort "#{e.filename}:#{e.line}:#{e.column}: #{e.message}\n#{e.excerpt}" end

Encoding errors are real here. json5-ruby accepts only UTF-8 or US-ASCII strings and does not transcode. A file read in another default encoding raises JSON5::EncodingError instead of being guessed at, so read with an explicit encoding: "UTF-8". See encoding problems for byte order marks and other causes.

Test icon

Conformance: What Each Gem Claims

I did not run the official json5-tests suite against any of these gems: no Ruby was available in the environment that wrote this page. The table below is a reading of each gem's grammar and code, plus what its own documentation says it tests. Treat a cell as "the source says so", not "I watched it pass". The wider picture is on the conformance page.

Behavior rb_json5 json5-ruby json5 (2014) smarter_json
Line and block comments Yes Yes Yes Yes
Single-quoted strings Yes Yes Yes Yes
Unquoted keys, ASCII Yes Yes Yes Yes
Unquoted keys with Unicode letters Yes Yes No Not verified
Hexadecimal numbers Yes Yes Unsigned only Yes
Signed hexadecimal (-0xFF) Yes Yes No Not verified
.5, 5. and +1 Yes Yes Yes Not verified
Infinity and NaN Yes Yes Infinity only; the NaN path calls an undefined method Yes
Rejects input that is not JSON5 Yes Yes Not verified No By design
Repeated keys Last wins, no option Last by default; first, error or keep all Raises SyntaxError Last by default; first on request; warns
Input limits None documented Yes Six, on by default No None documented
Keeps comments for editing No Read-side only (parse_document) No No
Writes JSON5 No No Source present, not usable JSON only

What the projects say about their own tests

  • rb_json5 says its RSpec suite and sample snippets derive from the json5-tests repository and from the reference implementation's parse.js and errors.js test files.
  • json5-ruby ships a generated conformance report against JSON5 1.0.0: 72 matrix rows, all marked covered, 33 specification-derived fixtures (22 positive, 11 negative), a fixed ECMAScript 5.1 lexical baseline (Unicode 3.0.0 tables), and deterministic fuzzing. It states plainly that the official JSON5 corpus is not vendored and that its coverage is derived from the specification. That is an honest claim, and it means a pass on the official suite is untested by its authors.
  • smarter_json does not aim for conformance. It documents itself as one superset of JSON5, HJSON and JSONC, so it adopts a feature unless it conflicts with another dialect. Its README lists accepted input that JSON5 forbids, such as underscores in numbers and unquoted string values.

If conformance matters to you, run the official json5-tests files through your chosen gem in your own CI. Each valid file should parse and each invalid one should raise. The expected results are in the specification overview.

Warning icon

Things That Will Surprise You

Each item below is read from the released source, not observed at runtime.

1. The gem named json5 is broken in places

Its parser is a line-by-line port of a JavaScript parser and still calls parseInt, isFinite, isNaN and String.fromCharCode, none of which exist in Ruby. I found no definition of any of them in the gem, so a \u escape or a NaN literal cannot parse. Plain input without those may parse, but I did not run it. It does raise on a repeated key. It also rejects signed hexadecimal such as -0xFF, which the specification allows, and its own source marks Unicode identifiers as a TODO. It has 2,142,271 downloads and was last released in 2014.

2. A rescue clause may not see its errors

The old gem raises SyntaxError, which is a ScriptError. A bare rescue => e only catches StandardError, so it falls straight through. Its escape table also writes '\b', '\f', '\r' and '\t' in single quotes, which Ruby keeps as a backslash plus a letter, not a control character.

3. Negative zero depends on the gem

JavaScript parses -0 to negative zero. In json5-ruby, the native number mode returns -0.0 for exactly that text. rb_json5 hands "-0" to Integer(), which gives plain 0. Switching gems can change a value that round-trips through a comparison.

4. Infinity and NaN become floats

Both strict parsers return Float::INFINITY and Float::NAN. Remember that NaN never equals itself, and that strict JSON writers refuse non-finite numbers: smarter_json's generator raises GenerateError unless you pass allow_nan: true.

5. Repeated keys disappear quietly

rb_json5 builds its hash from the member list, so the last value wins with no warning and no option. json5-ruby does the same by default but offers duplicate_keys: :error. The standard library's JSON.parse now rejects duplicates by default, so moving from JSON to a JSON5 gem can loosen a check you had.

6. A \u escape inside an unquoted key is checked against the wrong set

In rb_json5, the validation for an escape that appears after the first character of an unquoted key reuses the start-character patterns (letters, $, _). Reading the code, an escaped digit there would be rejected although the specification allows it. This is an edge case; quoted keys avoid it.

7. The gem name is not always the file you require

rb_json5 loads with require "rb_json5" and exposes RbJSON5 (note the capitals). json5-ruby loads with require "json5" and exposes JSON5. In a Gemfile, gem "json5-ruby" without require: "json5" leaves Bundler guessing a file name that does not exist.

JSON5 in Ruby: Common Questions

Does JSON.parse read JSON5?

Not a real file. With allow_comments and allow_trailing_comma it reads JSON plus comments and trailing commas. Single quotes, unquoted keys and hexadecimal numbers still fail, so use a gem.

Which gem should a new Rails app use?

rb_json5 for trusted files in the repository: it has the longest track record of the working parsers. json5-ruby if input may come from outside, since it is the only one with limits.

Can I replace database.yml or config_for files?

The Rails guide documents .yml files for config_for. Keep those as YAML. Use a JSON5 file for your own application settings, loaded in an initializer.

How do I write JSON5 from Ruby?

Write JSON with JSON.pretty_generate. It is valid JSON5. No gem emits comments, unquoted keys or trailing commas.

Is it safe to parse untrusted JSON5?

The parsers build data and never evaluate input as Ruby. The risk is resource use. Only json5-ruby documents limits, so cap size yourself for the others. The security tutorial covers the rest.

What does an error look like to the user?

Only json5-ruby gives you line, column and an excerpt as separate fields. For the common syntax mistakes and what they mean, see the error reference.