npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

json-inline-doc

v2.0.1

Published

Add inline comments on stringified JSON (JSONC), or generate from JSON schema

Downloads

15

Readme

JSON Inline Doc

Add inline comments on stringified JSON (JSONC), or generate from JSON schema

Use case: Using JSON for configuration and provide inline documentation as comments for users.

JSONC is JSON with JavaScript style comments. Please note that original JSON does not support comments.

Installation:

npm install json-inline-doc

Example - Comments Generated from JSON Schema

import { SchemaMetadataWriter } from 'json-inline-doc';

// Create a writer with a schema
const w: SchemaMetadataWriter = new SchemaMetadataWriter({
    "description": "Cluster Configuration",
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "description": "Cluster name"
        }
    },
    "required": []
});

// The API is the same as JSON.stringify
w.stringify({ name: 'Sample Cluster' }, null, 4);

Output:

/**
 * @type object
 * @description Cluster Configuration
 */
{
    /**
     * @type string
     * @description Cluster name
     */
    "name": "Sample Cluster"
}

Example - Custom Comments

import { CustomCommentWriter } from 'json-inline-doc';

// Create a writer
const w: CustomCommentWriter = new CustomCommentWriter();

// Add custom comments to fields
w.addComments([], [{ type: 'line', content: 'test' }]);
w.addComments(['test'], [{ type: 'block', content: 'test2' }]);
w.addComments(['test', 1], [{ type: 'end', content: 'test3' }]);
w.addComments(['test', undefined, undefined], [{ type: 'line', content: 'test4' }]);
w.addComments(['test', undefined, 'test2'], [{ type: 'block', content: path => path.toString() }]);

// The API is the same as JSON.stringify
console.log(w.stringify({ test: [{ test2: 3 }, { test2: 4 }, 3, [5]] }, null, 4));

Output:

// test
{
    /**
     * test2
     */
    "test": [
        {
            /**
             * test,0,test2
             */
            "test2": 3
        },
        {
            "test2": 4
        }, // test3
        3,
        [
            // test4
            5
        ]
    ]
}

For more detailed examples, please see the test cases.

API Documentation

All code is written in TypeScript which can be self-explanatory.

Writers

JSONCommentWriterBase

The abstract base class of all writers.

writer = new JSONCommentWriterBase(configuration)

  • Note: The above line of code is only for explanation. This class is abstract - do not try to new a instance by yourself!
  • configuration: object (optional)
    • emptyLineBeforeComments: boolean (default true)

      Add a blank line before every block and line comment, except comments of the followings:

      • The root object
      • The first item in array
      • The first key-value pair in object

      Not supported if space when calling stringify is 0.

    • spaceAroundCommentSymbol: boolean (default true)

      Add space around '//', '/*' and '*/'. '/*' and '*/' will not be affected by this configuration if styledBlockComment is true.

    • styledBlockComment: boolean (default true)

      Make block comment styled:

      • Asterisk (' * ') at the beginning of each line
      • The first line being '/**'
      • The last line being ' */'

      Not supported if space when calling stringify is 0. (Except for comments of root object)

    • maxLineLength: number (default 80)

      Maximum line length of each line of comment. Lines will be auto wrapped if exceeded. If any non-positive number is specified, auto wrapping will be disabled.

      Not supported if space when calling stringify is 0. (Except for comments of root object)

writer.stringify(value, replacer, space)

  • Convert value to JSON string with comments.
  • The signature is the same as JSON.stringify
  • JSON stringify implementation is based on the following code: https://github.com/douglascrockford/JSON-js/blob/2a76286e00cdc1e98fbc9e9ec6589563a3a4c3bb/json2.js

CustomCommentWriter

A class of JSON comment writer which supports custom comments for fields specified by path.

writer = new CustomCommentWriter(configuration)

writer.addComments(selector, comments)

  • Add custom comments to fields specified by selector.

  • selector: (string | number | undefined)[] (required)

    A path of keys. undefined can be used to match any other key not matched on that level. An empty array matches the root object.

  • comments: IJSONComment[] (required)

    Comments to be shown when the selector matches.

SchemaMetadataWriter

A class of JSON comment writer generating comments for fields specified in JSON schema.

writer = new SchemaMetadataWriter(schemaObject, commentGenerator, configuration)

  • Construct a new SchemaMetadataWriter.

  • schemaObject: JSONSchema (required)

    A fully dereferenced JSON schema object containing no $ref, which can be obtained using libraries like json-schema-ref-parser.dereference with circular being true.

    This object is allowed to be recursive.

  • commentGenerator: function (defaults to a simple schema comment generator)

    A function to generate comment string from the schema of a field.

    Signature: (schema: JSONSchema) => IJSONComment | undefined

  • configuration: object (optional)

    Please refer to the constructor of JSONCommentWriterBase.

Types

IJSONComment

Represents a single comment. Can be an object or a string.

  • When being a string:

    The comment will be assumed to be a block comment (see below), and the string will be the content of comment.

  • When being an object:

    • type: 'block' | 'line' | 'end' (required)

      Type of the comment:

      • block - block comment wrapped with '/*' and '*/' before the item
      • line - line comment beginning with '//' before the item
      • end - line comment at the end of the item on the same line

      line and end are not supported if space when calling stringify is 0. (Except for comments of root object)

    • content: string or function (required)

      Content of the comment. Could be:

      • A single-line or multi-line string
      • A function to be called when stringifying the matched field.
        • Signature: (matchedFieldPath: (string | number)[]) => string | undefined
        • Return undefined to omit.
      • '*/' will be escaped automatically if type is block.

License

MIT license