hjson vs json5 vs strip-json-comments
JSON Parsing and Manipulation
hjsonjson5strip-json-commentsSimilar Packages:

JSON Parsing and Manipulation

JSON Parsing and Manipulation libraries in JavaScript provide tools for working with JSON (JavaScript Object Notation) data, which is a widely used format for data interchange. These libraries offer features for parsing JSON strings into JavaScript objects, serializing objects into JSON format, and manipulating JSON data with greater flexibility and ease. They often include enhancements over the native JSON methods, such as better handling of comments, support for non-standard syntax, and more customizable serialization options. This makes them valuable for web development, APIs, and any application that interacts with JSON data.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
hjson0431-276 years agoMIT
json507,130235 kB40-MIT
strip-json-comments06248.2 kB010 months agoMIT

Feature Comparison: hjson vs json5 vs strip-json-comments

Comment Support

  • hjson:

    hjson supports comments natively, allowing both single-line (//) and multi-line (/* ... */) comments. This makes it easy to document your data directly within the file without any additional processing.

  • json5:

    json5 also supports comments, including single-line and multi-line comments. This feature allows for better documentation and clarity within JSON5 files, making them easier to understand.

  • strip-json-comments:

    strip-json-comments is specifically designed to remove comments from JSON strings. It does not support comments itself but provides a way to strip them out, ensuring the resulting JSON is valid.

Syntax Flexibility

  • hjson:

    hjson offers a more relaxed syntax compared to standard JSON, allowing for features like multi-line strings, unquoted keys, and more. This flexibility makes it easier to write and read, especially for configuration files.

  • json5:

    json5 is a superset of JSON that allows for unquoted keys, trailing commas, and more lenient parsing. This makes it more forgiving and easier to work with, especially when dealing with large or complex data structures.

  • strip-json-comments:

    strip-json-comments does not alter the syntax of JSON; it simply removes comments. It is a lightweight tool that ensures your JSON remains compliant while allowing you to include comments during development.

Use Case

  • hjson:

    hjson is ideal for configuration files, data interchange where readability is important, and scenarios where you want to allow more human-friendly input while still being able to convert to standard JSON.

  • json5:

    json5 is suitable for any application that can benefit from a more flexible JSON format, including configuration files, data serialization, and APIs that can handle the extended syntax.

  • strip-json-comments:

    strip-json-comments is perfect for preprocessing JSON files or strings that contain comments, making it useful for projects that want to maintain standard JSON compliance while allowing comments in the source files.

Example Code

  • hjson:

    Example of hjson with comments and relaxed syntax:

    {
      // This is a comment
      name: "John Doe",  // Inline comment
      age: 30,
      hobbies: [
        "reading",
        /* This is a multi-line comment
           that explains the hobbies
        */
        "hiking",
        "coding"
      ],
      address: {
        street: "123 Main St",
        city: "Anytown",
        zip: "12345"
      }
    }
    
  • json5:

    Example of json5 with comments and flexible syntax:

    {
      // This is a comment
      name: "Jane Doe", // Unquoted key
      age: 25,
      hobbies: [
        "painting",
        "traveling",
        "music",
        // Trailing comma
      ],
      address: {
        street: "456 Elm St",
        city: "Othertown",
        zip: "67890",
      }
    }
    
  • strip-json-comments:

    Example of using strip-json-comments to remove comments:

    const stripJsonComments = require('strip-json-comments');
    
    const jsonWithComments = `{
      // This is a comment
      "name": "Alice", // Inline comment
      "age": 28,
      "hobbies": [
        "drawing",
        "cycling" // Another comment
      ]
      /* Multi-line comment */
    }`;
    
    const jsonWithoutComments = stripJsonComments(jsonWithComments);
    console.log(jsonWithoutComments);
    // Output:
    // {
    //   "name": "Alice",
    //   "age": 28,
    //   "hobbies": [
    //     "drawing",
    //     "cycling"
    //   ]
    // }
    

How to Choose: hjson vs json5 vs strip-json-comments

  • hjson:

    Choose hjson if you need a human-friendly JSON format that supports comments, multi-line strings, and more relaxed syntax while still being easily convertible to standard JSON. It is ideal for configuration files and scenarios where readability is a priority.

  • json5:

    Select json5 if you want to work with a superset of JSON that allows for comments, trailing commas, and unquoted keys, making it more flexible and forgiving than standard JSON. It is great for projects that require a more lenient syntax while maintaining compatibility with JSON.

  • strip-json-comments:

    Use strip-json-comments if you only need to remove comments from JSON strings before parsing them. This lightweight package is perfect for situations where you want to keep your JSON files standard-compliant but still want to include comments for documentation purposes.

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