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
DolphinDB JavaScript API is a JavaScript library that encapsulates the ability to operate the DolphinDB database, such as: connecting to the database, executing scripts, calling functions, uploading variables, etc.

DolphinDB JavaScript API English | 中文 Overview DolphinDB JavaScript API is a JavaScript library that encapsulates the ability to operate the DolphinDB

DolphinDB 6 Dec 12, 2022
ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used

null 30.1k Jan 3, 2023
🔄 A realtime Database for JavaScript Applications

RxDB A realtime Database for JavaScript Applications RxDB (short for Reactive Database) is a NoSQL-database for JavaScript Applications like Websites,

Daniel Meyer 18.6k Dec 31, 2022
A javascript library to run SQLite on the web.

SQLite compiled to JavaScript sql.js is a javascript SQL database. It allows you to create a relational database and query it entirely in the browser.

SQL.JS 11k Jan 7, 2023
Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.

Lovefield Lovefield is a relational database written in pure JavaScript. It provides SQL-like syntax and works cross-browser (currently supporting Chr

Google 6.8k Jan 3, 2023
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

Please use version 1.x as prior versions has a security flaw if you use user generated data to concat your SQL strings instead of providing them as a

Andrey Gershun 6.1k Jan 9, 2023
A pure node.js JavaScript Client implementing the MySQL protocol.

mysql Table of Contents Install Introduction Contributors Sponsors Community Establishing connections Connection options SSL options Connection flags

null 17.6k Jan 1, 2023
The JavaScript Database, for Node.js, nw.js, electron and the browser

The JavaScript Database Embedded persistent or in memory database for Node.js, nw.js, Electron and browsers, 100% JavaScript, no binary dependency. AP

Louis Chatriot 13.2k Jan 2, 2023
Adapter based JavaScript ORM for Node.js and the browser

firenze.js A database agnostic adapter-based object relational mapper (ORM) targetting node.js and the browser. Visit http://firenze.js.org for docume

Fahad Heylaal 130 Jul 14, 2022
This is very simple game catch word with JavaScript and Jquery

Catch-Word-js This is very simple game catch word with JavaScript and Jquery install and run guide! download project zip! extract zip file on any dire

Jortsoft 14 Nov 26, 2022
curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.

graphqurl graphqurl is a curl like CLI for GraphQL. It's features include: CLI for making GraphQL queries. It also provisions queries with autocomplet

Hasura 3.2k Jan 3, 2023
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.

Downloadify: Client Side File Creation Important! The swf has been compiled for online use only. Testing from the file path (i.e. file:// ) will not w

Doug Neiner 853 Nov 21, 2022
A tool to inject javascript into the Steam Deck client.

Steam Deck UI Inject A tool to inject javascript into the Steam Deck client. How it works This tool works by taking advantage of the remote debugging

marios 30 Dec 5, 2022
XML/HTML parser and processing library for JavaScript and TypeScript

[VIEW DOCUMENTATION] Robin is an XML parser and processing library that supports a sane version of HTML. It features a set of DOM utilities, including

null 15 Oct 5, 2022
A javascript REST ORM that is offline and real-time capable

Rekord Rekord is an ORM - a way to define properties and relationships - that interacts with local storage, a RESTful service, and a real-time service

Rekord 177 Oct 18, 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