Hjson for JavaScript

Overview

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

Comments
  • Option mltabs to emit m-lines when string contains tabs

    Option mltabs to emit m-lines when string contains tabs

    Many thanks for a great project!

    This PR add support for generating triple quoted multiple lines even if the string value contains \t characters:

    Hjson.stringify(value, { mltabs: true }
    

    It is exposed on the command line as the flag -mltab

    hjson-mltabs

    I have not figured out why the tab character would be a problem for triple quotes multiple lines. Let me know if I missed the obvious.

    Thanks!

    opened by hmalphettes 11
  • Readable compact format

    Readable compact format

    Is there a "compact but readable" format for HJSON? Something like https://github.com/lydell/json-stringify-pretty-compact for JSON?

    Thanks!

    opened by nyurik 9
  • add support for comma separator between elements - fixes #17

    add support for comma separator between elements - fixes #17

    Feel free to provide feedback of any kind. Things you want differently (code style, documentation wording, option name).

    I wanted to add tests for this as well but I couldn't get a grip on how these work in this project :).

    opened by SamVerschueren 8
  • Support ES5 style multiline strings using backtick

    Support ES5 style multiline strings using backtick

    Hello! First: thanks for this awesome module! It does exactly what I need. I would love to propose multiline strings using the backtick - as introduced with ES5.

    e.g.:

    {
        string: `multi
            line
            testing
        `
    }
    

    Your thoughts?

    opened by MartinMuzatko 6
  • Bad String for Newline in String

    Bad String for Newline in String

    Hello, Having a giant hjson file containing language strings like:

    "en": "hello I am a potentially very long String"

    I use it as a Module inside a Javascript App - there it works perfectly in in the current way. Using the cli it give's me the error:

    Error: Bad string containing newline at line 153,106

    SO basicly there are tons of these cases where I have like:

    "en": "hello I am such a long string that I will become continued
    in the next line"
    

    It would be awesome if this would't be a such a big deal :-)

    opened by JhonnyJason 5
  • Why not support for single quote string?

    Why not support for single quote string?

    I expect hjson

    a: 'test'
    

    to represent

    {
      "a": "test"
    }
    

    But I only get

    {
      "a": "'test'"
    }
    

    If you don't want to break the spec, please add an option to enable it.

    opened by ysmood 5
  • Suggestions?

    Suggestions?

    I can't find a comment area for https://news.ycombinator.com/item?id=7435111 so I just say something here. ;-)

    Although HJSON is a superset of JSON, but the syntax of YAML is really better than it for humans. I don't think people like to add so much { } and [ ] just for communication between humans (this is a rare case?).

    I think a YAML-JSON converter is better than hjson-js.

    opened by jakwings 5
  • hjson-comments.extract/merge doesn't roundtrip array comments correctly.

    hjson-comments.extract/merge doesn't roundtrip array comments correctly.

    When trying to extract comments from the following hjson:

    {
        a: 1,
        b: 2, # comment
        c: [
            'x',
            'y', #why?
            'z' // zee
        ]
    }
    

    you wind up with:

    {
      a: 1
      b: 2 # comment
      c:
      [
        "x" #why?
        "y" // zee
        z
      ]
    }
    

    That is because extract is putting the comments into a sparse array a which only has elements for entries with comments (this will not hold up if the comments are themselves serialized to JSON). When merge is called, it is looping over all array elements and then transferring the comments to the current value.COMMENTS, but it is using push and losing all index information.

    opened by ygraber 4
  • CLI to write back to hjson

    CLI to write back to hjson

    Hello! I'm using hjson in combination with jq to read from hjson on the commandline. See https://jqplay.org/s/pD2ADtE_rn

    I would like to be able to write to hjson file via terminal. Right now this is not possible.

    Suggested syntax:

    hjson -s .test "newstring"
    

    Let me know what you think!

    opened by MartinMuzatko 4
  • How do I use options?

    How do I use options?

    Can you please explain how to use options on var text2 = Hjson.stringify(obj); after everything is being parsed I would like to add quotes to all my original json strings.

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

    after this is being done, I get a stripped down code.

    opened by tmamedbekov 4
  • New option to format arrays of simple values (strings, numbers, bools) on a single line.

    New option to format arrays of simple values (strings, numbers, bools) on a single line.

    I added a simple option "inlineSimple" which formats arrays of simple values comma-separated on a single line. This can improve readability in some cases.

    This

    [
       "value1"
       "value2"
       "value3"
      10
      11
    ]
    

    with inlineSimple=true is formatted as:

    [ "value1", "value2", "value2", 10, 11 ]
    
    opened by kay999 4
  • emitRootBraces was removed?

    emitRootBraces was removed?

    From the README:

    emitRootBraces: boolean, show braces for the root object. Default true.

    This is a useful option for making my output look neater, so I tried turning it on and spent a lot of time scratching my head wondering why it wasn't working. Turns out this was removed in 2b96ade57e9d675ddc5fe037ff95c6744d89c22e, but:

    1. the documentation wasn't updated accordingly, and
    2. that commit doesn't explain the justification for the removal.

    I notice that the Hjson syntax says:

    Note: This feature was previously marked as deprecated but is now officially supported again.

    So maybe this option should be brought back again?

    opened by wolfgang42 0
  • When written with `keepWsc: true,` carries comments

    When written with `keepWsc: true,` carries comments

    raw hjson string

    var text = '{\
        "last.access": true,\
        // "last.set": true,\
        // "skills.use": true,\
        // "last.wrap.*": true,\
    }';
    

    parse it and then base it back into text

    var data = HJSON.parse(text, {keepWsc: true});
    text = HJSON.stringify(data, {
        keepWsc: true,
        bracesSameLine: true,
        quotes: 'all',
        separator: true,
        space: '\t',
    });
    

    as a result, we get the following string

    '{\
        "last.access": true    // "last.set": true,\
        // "skills.use": true,\
        // "last.wrap.*": true,\
    }';
    

    repeating these steps several times teaching such a line

    '{\
        "last.access": true    // "last.set": true,    // "skills.use": true,    // "last.wrap.*": true,\
    }';
    
    opened by lastuniverse 0
  • Parse removes newline for comment if it last entry in entity

    Parse removes newline for comment if it last entry in entity

    I have faced strange behavior of comment processing if it is last entry in object

    let parsed = hjson.rt.parse("{\n  a:1/n    // comment 1/n. b: 2\n  //comment 2\n}");
    hjson.rt.stringify(parsed) // "{\n  a:1/n    // comment 1/n. b: 2  //comment 2\n}"
    

    Notice that \n disappeared before //comment 2; As use case it means that if user commented last property of object, after parse/stringify methods, commented property will jump to the previous line So this object

    {
        a:1
        // b:2
    }
    

    after parse/stringify methods will become this

    {
        a:1 // b:2
    }
    
    opened by bdruzhynin 0
  • fix: sortProps not working

    fix: sortProps not working

    I tried to use sortProps option to sort properties, but it didn't work. So I've changed code as the commit to make it work.

    Please review my changes, if something more needed, just let me know. Regards.

    opened by gnseo 2
  • The require-config features demands .hjson extension

    The require-config features demands .hjson extension

    Is there a particular reason that the hjson/lib/require-config feature only works if the subsequently-required file has a .hjson extension? The feature seems to be disabled if you require a .json file, with subsequent parsing errors. Just wondering what the rationale was here.

    This project is a great contribution to sanity, thank you!

    opened by john-aws 0
Owner
Hjson
A user interface for JSON.
Hjson
ClojureScript's persistent data structures and supporting API from the comfort of vanilla JavaScript

mori A simple bridge to ClojureScript's persistent data structures and supporting APIs for vanilla JavaScript. Pull requests welcome. Breaking changes

David Nolen 3.4k Dec 31, 2022
A complete, fully tested and documented data structure library written in pure JavaScript.

Buckets A JavaScript Data Structure Library Buckets is a complete, fully tested and documented data structure library written in pure JavaScript. Incl

Mauricio 1.2k Jan 4, 2023
HashMap JavaScript class for Node.js and the browser. The keys can be anything and won't be stringified

HashMap Class for JavaScript Installation Using npm: $ npm install hashmap Using bower: $ bower install hashmap You can download the last stable ver

Ariel Flesler 381 Sep 24, 2022
Immutable persistent data collections for Javascript which increase efficiency and simplicity.

Immutable collections for JavaScript Immutable data cannot be changed once created, leading to much simpler application development, no defensive copy

Immutable.js 32.4k Jan 7, 2023
A tiny JavaScript utility to access deep properties using a path (for Node and the Browser)

object-path Access deep properties using a path Changelog 0.11.5 SECURITY FIX. Fix a prototype pollution vulnerability in the set() function when usin

Mario Casciaro 1k Dec 29, 2022
An isomorphic and configurable javascript utility for objects deep cloning that supports circular references.

omniclone An isomorphic and configurable javascript function for object deep cloning. omniclone(source [, config, [, visitor]]); Example: const obj =

Andrea Simone Costa 184 May 5, 2022
Hjson for JavaScript

hjson-js Hjson, a user interface for JSON JSON is easy for humans to read and write... in theory. In practice JSON gives us plenty of opportunities to

Hjson 387 Dec 20, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules to write modular JavaScript.

To-Do-List App This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules

Samuel Mwape 18 Sep 20, 2022
The best JavaScript Data Table for building Enterprise Applications. Supports React / Angular / Vue / Plain JavaScript.

Module SonarCloud Status ag-grid-community ag-grid-enterprise AG Grid AG Grid is a fully-featured and highly customizable JavaScript data grid. It del

AG Grid 9.5k Dec 30, 2022
A transparent, in-memory, streaming write-on-update JavaScript database for Small Web applications that persists to a JavaScript transaction log.

JavaScript Database (JSDB) A zero-dependency, transparent, in-memory, streaming write-on-update JavaScript database for the Small Web that persists to

Small Technology Foundation 237 Nov 13, 2022
Reference for How to Write an Open Source JavaScript Library - https://egghead.io/series/how-to-write-an-open-source-javascript-library

Reference for How to Write an Open Source JavaScript Library The purpose of this document is to serve as a reference for: How to Write an Open Source

Sarbbottam Bandyopadhyay 175 Dec 24, 2022
Traceur is a JavaScript.next-to-JavaScript-of-today compiler

What is Traceur? Traceur is a JavaScript.next-to-JavaScript-of-today compiler that allows you to use features from the future today. Traceur supports

Google 8.2k Dec 31, 2022
Dynamic tracing for javascript, in javascript (similar dtrace, ktap etc)

jstrace Dynamic tracing for JavaScript, written in JavaScript, providing you insight into your live nodejs applications, at the process, machine, or c

null 387 Oct 28, 2022
Open Source projects are a project to improve your JavaScript knowledge with JavaScript documentation, design patterns, books, playlists.

It is a project I am trying to list the repos that have received thousands of stars on Github and deemed useful by the JavaScript community. It's a gi

Cihat Salik 22 Aug 14, 2022
Javascript-testing-practical-approach-2021-course-v3 - Javascript Testing, a Practical Approach (v3)

Javascript Testing, a Practical Approach Description This is the reference repository with all the contents and the examples of the "Javascript Testin

Stefano Magni 2 Nov 14, 2022