hjson vs json5
Choosing the Right Relaxed JSON Parser for Configuration and Data Exchange
hjsonjson5Similar Packages:

Choosing the Right Relaxed JSON Parser for Configuration and Data Exchange

hjson and json5 are both libraries designed to parse human-friendly variations of JSON, addressing the strict syntax limitations of standard JSON (such as no comments, no trailing commas, and mandatory quotes on keys). While they share the goal of improving readability for configuration files and data literals, they differ significantly in their syntax extensions and primary use cases. json5 aims to be a strict superset of JSON, adding ECMAScript 5 features like single-line comments, trailing commas, and unquoted keys, making it ideal for config files that need to be read by both humans and machines. hjson (Human JSON) goes further by adopting a minimalist syntax that often omits quotes and braces entirely, prioritizing ease of manual editing over strict compatibility with JSON parsers, making it best suited for configuration files edited directly by users.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
hjson0432-276 years agoMIT
json507,153235 kB39-MIT

Hjson vs JSON5: Syntax, Compatibility, and Use Cases Compared

When working with configuration files, data mocks, or any scenario where humans need to write structured data, standard JSON often feels too rigid. Missing commas, forgotten quotes, and the inability to add comments lead to frequent syntax errors. Both hjson and json5 solve this by offering relaxed parsers, but they take very different philosophical approaches to what "relaxed" means. Let's dive into how they handle syntax, compatibility, and real-world usage.

πŸ“ Syntax Philosophy: Minimalist vs. JavaScript-Like

The core difference lies in how much they deviate from standard JSON.

hjson prioritizes human typing speed and visual clarity. It removes as much punctuation as possible. You don't need quotes for keys or string values (unless they contain special characters), you can skip colons, and you can omit braces for the root object. It looks more like a properties file or YAML.

// hjson example
{
  # Comments use hash or slash
  name: John Doe
  age: 30
  skills: [
    javascript
    rust
  ]
  # No quotes needed for simple strings
  role: admin
}

json5 aims to be a valid ECMAScript 5 object literal. It keeps the structure of JSON intact (braces, colons, commas are still expected) but relaxes the rules around them. You can add comments, use trailing commas, and drop quotes on keys if they are valid identifiers. It feels like writing a JavaScript object.

// json5 example
{
  // Comments use slash
  name: 'John Doe',
  age: 30,
  skills: [
    'javascript',
    'rust',
  ], // Trailing comma allowed
  role: 'admin', // Single or double quotes
}

πŸ”Œ Compatibility with Standard JSON

This is often the deciding factor for architectural decisions.

json5 is a strict superset of JSON. Any valid JSON file is also valid JSON5. This means you can incrementally adopt it; you can start with a standard JSON file and slowly add comments or trailing commas without breaking the parser. If you strip the comments and trailing commas, you are back to standard JSON.

// Valid JSON is also valid JSON5
{
  "key": "value",
  "number": 123
}
// JSON5 parser accepts this without changes

hjson is NOT a superset of JSON in practice because its default output and parsing expectations differ. While it can parse standard JSON, its canonical format omits characters that standard JSON parsers require. If you save an hjson file in its natural style (no quotes, no colons), a standard JSON.parse() will fail immediately. You must always use the hjson parser to read it, or compile it down to standard JSON before passing it to other systems.

// Valid hjson, but INVALID standard JSON
{
  key: value
}
// Standard JSON.parse() throws an error here

πŸ’¬ Comments and Trailing Commas

Both libraries solve the two biggest pain points of standard JSON: comments and trailing commas.

hjson supports comments using # (hash) or // (double slash). This makes it very friendly for shell-script users or those who prefer hash comments. It naturally handles trailing commas since the list syntax is flexible.

# hjson comment style
items: [
  one
  two # last item, no comma needed
]

json5 supports only // and /* */ comments, matching JavaScript style. It explicitly allows trailing commas in arrays and objects, which is a huge win for version control diffs (adding a new item doesn't change the previous line).

// json5 comment style
items: [
  'one',
  'two', // Trailing comma is safe
]

πŸ› οΈ Real-World Usage Scenarios

Scenario 1: User-Editable Configuration Files

If you are building a CLI tool or an application where users manually edit config files, hjson often provides a better experience. Users don't have to worry about syntax errors from missing quotes or commas.

# config.hjson
# User edits this directly
port: 8080
debug: true
allowedHosts: [
  localhost
  example.com
]

Scenario 2: Build Tool Configurations

For build tools, bundlers, or project settings where the file might be touched by both humans and automated scripts, json5 is usually safer. Many modern tools (like Babel, ESLint, and Webpack) support JSON5 or similar JS-based configs because the structure remains predictable.

// .eslintrc.json5
{
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['eslint:recommended'],
  // Easy to add new rules without fixing commas
  rules: {
    'no-console': 'warn',
  },
}

Scenario 3: Data Exchange Between Services

If you need to pass data between microservices where one service might use a standard library, neither is ideal without a compilation step. However, if you must choose, json5 is easier to sanitize back to standard JSON programmatically since the structure is already there. With hjson, you rely entirely on the hjson.stringify() method to produce valid JSON for transmission.

// Converting hjson to standard JSON for API transmission
const Hjson = require('hjson');
const fs = require('fs');

const raw = fs.readFileSync('config.hjson', 'utf8');
const obj = Hjson.parse(raw);
const standardJson = JSON.stringify(obj); // Now safe to send

⚠️ When to Avoid These Libraries

While these tools are powerful, they introduce a dependency and a parsing step.

  • Avoid hjson if you are working in an environment where installing extra packages is difficult or if the config needs to be read by languages with robust JSON parsers but no Hjson ports (though many exist, JSON is universal).
  • Avoid json5 if you need the absolute highest performance for parsing massive datasets. The relaxed parsing logic is slightly slower than native JSON.parse(). For huge data files, stick to standard JSON or binary formats like MessagePack.
  • Do not use either for untrusted input without validation. Relaxed parsers can sometimes be more prone to injection attacks if not carefully sandboxed, although both libraries are generally mature. Always validate the resulting object schema.

πŸ“Œ Summary Table

Featurehjsonjson5
Primary GoalHuman readability, minimal typingJS Object literal compatibility
Quotes on KeysOptional (often omitted)Optional (if valid identifier)
ColonsOptionalRequired
BracesOptional for rootRequired
Comments# and //// and /* */
Trailing CommasSupportedSupported
Standard JSON SupersetNo (canonical format differs)Yes
Best ForUser-edited configs, CLI toolsBuild configs, dev tooling

πŸ’‘ The Big Picture

hjson is like writing a note to a friend β€” it skips the formalities to get the point across quickly. It's perfect for configuration files where a human is the primary writer and reader. The lack of punctuation noise makes it incredibly fast to edit.

json5 is like writing formal code β€” it keeps the structure strict but allows modern conveniences. It's the right choice when you want the benefits of comments and trailing commas but still want the file to look and behave like a standard JSON object, ensuring smoother integration with existing JSON-based toolchains.

Final Thought: If your config is strictly for humans and simplicity is king, go with hjson. If your config lives in a developer ecosystem where tools might also read it, json5 offers the safer, more compatible path.

How to Choose: hjson vs json5

  • hjson:

    Choose hjson if your primary use case is configuration files that will be manually edited by end-users or developers who value brevity and minimal typing. Its syntax allows omitting quotes, colons, and even braces, making it extremely clean for simple key-value pairs. However, avoid it if you need to share data with systems that strictly expect standard JSON or if you require complex nested structures that benefit from explicit delimiters. It is best for internal tooling, CLI configs, or scenarios where the file is converted to standard JSON before being consumed by other services.

  • json5:

    Choose json5 if you need a configuration format that feels like JavaScript object literals and maintains high compatibility with standard JSON structures. It is the superior choice when you need comments, trailing commas, and unquoted keys but still want the file to look structurally identical to JSON. Use json5 for build configurations, bundler settings, or data exchange formats where the file might occasionally be processed by tools that can fall back to standard JSON parsing. It strikes the best balance between human readability and machine predictability.

README for hjson

hjson-js

Build Status NPM version License

Hjson, a user interface for JSON

Hjson Intro

JSON is easy for humans to read and write... in theory. In practice JSON gives us plenty of opportunities to make mistakes without even realizing it.

Hjson is a syntax extension to JSON. It's NOT a proposal to replace JSON or to incorporate it into the JSON spec itself. It's intended to be used like a user interface for humans, to read and edit before passing the JSON data to the machine.

{
  # specify rate in requests/second (because comments are helpful!)
  rate: 1000

  // prefer c-style comments?
  /* feeling old fashioned? */

  # did you notice that rate doesn't need quotes?
  hey: look ma, no quotes for strings either!

  # best of all
  notice: []
  anything: ?

  # yes, commas are optional!
}

The JavaScript implementation of Hjson is based on JSON-js. For other platforms see hjson.github.io.

Install from npm

npm install hjson

Usage

var Hjson = require('hjson');

var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);

To keep comments intact see API.

From the Commandline

Install with npm install hjson -g.

Usage:
  hjson [OPTIONS]
  hjson [OPTIONS] INPUT
  hjson (-h | --help | -?)
  hjson (-V | --version)

INPUT can be in JSON or Hjson format. If no file is given it will read from stdin.
The default is to output as Hjson.

Options:
  (-j | -json)  output as formatted JSON.
  (-c | -json=compact)  output as JSON.
Options for Hjson output:
  -sl         output the opening brace on the same line
  -quote      quote all strings
  -quote=all  quote keys as well
  -js         output in JavaScript/JSON compatible format
              can be used with -rt and // comments
  -rt         round trip comments
  -nocol      disable colors
  -cond=n     set condense option (default 60, 0 to disable)

Domain specific formats are optional extensions to Hjson and can be enabled with the following options:
  +math: support for Inf/inf, -Inf/-inf, Nan/naN and -0
  +hex: parse hexadecimal numbers prefixed with 0x
  +date: support ISO dates

Sample:

  • run hjson -j test.hjson > test.json to convert to JSON
  • run hjson test.json > test.hjson to convert to Hjson
  • run hjson test.json to view colorized output

API

The API is the same for the browser and node.js version.

NOTE that the DSF api is considered experimental

Hjson.parse(text, options)

This method parses JSON or Hjson text to produce an object or array.

  • text: the string to parse as JSON or Hjson
  • options: object
    • keepWsc: boolean, keep white space and comments. This is useful if you want to edit an hjson file and save it while preserving comments (default false)

Hjson.stringify(value, options)

This method produces Hjson text from a JavaScript value.

  • value: any JavaScript value, usually an object or array.
  • options: object
    • keepWsc: boolean, keep white space. See parse.
    • condense: integer, will try to fit objects/arrays onto one line. Default 0 (off).
    • bracesSameLine: boolean, makes braces appear on the same line as the key name. Default false.
    • emitRootBraces: boolean, show braces for the root object. Default true.
    • quotes: string, controls how strings are displayed. (setting separator implies "strings")
      • "min": no quotes whenever possible (default)
      • "keys": use quotes around keys
      • "strings": use quotes around string values
      • "all": use quotes around keys and string values
    • multiline: string, controls how multiline strings are displayed. (setting quotes implies "off")
      • "std": strings containing \n are shown in multiline format (default)
      • "no-tabs": like std but disallow tabs
      • "off": show in JSON format
    • separator: boolean, output a comma separator between elements. Default false
    • space: specifies the indentation of nested structures. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or 'Β '), it contains the characters used to indent at each level.
    • eol: specifies the EOL sequence (default is set by Hjson.setEndOfLine())
    • colors: boolean, output ascii color codes
    • serializeDeterministically: boolean, when serializing objects into hjson, order the keys based on their UTF-16 code units order. Default false.

Hjson.endOfLine(), .setEndOfLine(eol)

Gets or sets the stringify EOL sequence ('\n' or '\r\n'). When running with node.js this defaults to os.EOL.

Hjson.rt { parse, stringify }

This is a shortcut to roundtrip your comments when reading and updating a config file. It is the same as specifying the keepWsc option for the parse and stringify functions.

Hjson.version

The version number.

require-hook

Require a config file directly.

require("hjson/lib/require-config");
var cfg=require("./config.hjson");

modify & keep comments

You can modify a Hjson file and keep the whitespace & comments intact (round trip). This is useful if an app updates its config file.

// parse, keep whitespace and comments
// (they are stored in a non enumerable __COMMENTS__ member)
var data = Hjson.rt.parse(text);

// modify like you normally would
data.foo = "text";

// convert back to Hjson
console.log(Hjson.rt.stringify(data));

Build

To run all tests and create the bundle output, first install the dev dependencies with npm i and then run npm run build.

History

see history.md