hjson vs json5
JSON Parsing and Serialization
hjsonjson5Similar Packages:

JSON Parsing and Serialization

hjson and json5 are libraries that extend the JSON format to make it more human-friendly while remaining compatible with JavaScript. They allow for more flexible syntax, such as comments, unquoted keys, and trailing commas, which can make configuration files and data structures easier to read and write. hjson focuses on providing a more readable format with features like multi-line strings and better handling of whitespace, while json5 aims to enhance JSON with a minimal set of changes to improve its usability without sacrificing compatibility.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
hjson393,605433-265 years agoMIT
json507,089235 kB39-MIT

Feature Comparison: hjson vs json5

Readability

  • hjson:

    hjson significantly improves readability by allowing comments, multi-line strings, and a more relaxed syntax that reduces the need for quotes and braces. This makes it easier for humans to write and understand configuration files.

  • json5:

    json5 enhances readability by allowing unquoted keys, trailing commas, and comments (though comments are not supported in all parsers). These features make JSON5 files easier to edit while still being relatively close to standard JSON.

Compatibility

  • hjson:

    hjson is not fully compatible with standard JSON due to its relaxed syntax and additional features. However, it provides a parser that can convert HJSON back to JSON, making it suitable for applications that can handle the conversion.

  • json5:

    json5 is designed to be compatible with existing JSON parsers, with the main exception being that not all parsers support its additional features (like unquoted keys and trailing commas). This makes JSON5 a good choice for projects that need to integrate with standard JSON while benefiting from its enhancements.

Comment Support

  • hjson:

    hjson fully supports comments, allowing developers to add explanations and notes directly within the data. This is particularly useful for configuration files where context may be needed.

  • json5:

    json5 also supports comments, including single-line (//) and multi-line (/* ... */) comments. This feature helps improve the clarity of JSON5 files, especially in complex structures.

Multi-line Strings

  • hjson:

    hjson supports multi-line strings natively, allowing for more natural representation of text blocks without the need for escape characters. This feature is especially useful for storing large text data or documentation within the file.

  • json5:

    json5 does not have built-in support for multi-line strings, but it allows for them using standard JavaScript string syntax (e.g., using backticks for template literals). However, this is not as seamless as HJSON's multi-line string support.

Example Code

  • hjson:

    Example of HJSON with comments and multi-line strings:

    {
      // This is a comment
      key: "value",  // Inline comment
      multiLine: "This is a multi-line string\
      that spans multiple lines.",
      list: [1, 2, 3],
    }
    
  • json5:

    Example of JSON5 with comments and unquoted keys:

    {
      // This is a comment
      unquotedKey: "value",
      trailingComma: "value",
      list: [1, 2, 3,], // Trailing comma
    }
    

How to Choose: hjson vs json5

  • hjson:

    Choose hjson if you prioritize readability and want a format that allows for comments, multi-line strings, and more relaxed syntax. It is particularly useful for configuration files where human editing is common.

  • json5:

    Choose json5 if you need a lightweight solution that adds a few simple features to JSON, such as unquoted keys and trailing commas, while maintaining a focus on compatibility with existing JSON parsers. It is ideal for projects that require a minimalistic approach to enhancing JSON.

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