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

ask-json

v0.1.9

Published

Easy interactive prompts to create and validate data using JSON schema

Downloads

147

Readme

AskJSON

Easy interactive prompts to create and validate data using JSON schema.

npm version Reuters open source software

Why this?

We use JSON files to hold important configuration like the metadata for our published pages. But filling out those files is often tedious and prone to error.

Using JSON schema helps us ensure config files contain the correct information. ask-json gives us a way to make filling out and validating those files easy. It hooks into our workflow and creates an interactive step to validate configuration before it's used.

What's it do?

ask-json lets you turn any JSON schema into an interactive CLI prompt. Just create a schema with some validation rules. ask-json will ask for any required information using friendly, data-type specific prompts from prompts.js.

It's best used to check an existing JSON file, correct invalid and missing information and write that data back to the file.

Install

$ npm install ask-json

or

$ yarn add ask-json

Prereqs: JSON schema

ask-json is driven by JSON schema validation. Check out the official docs to learn more about the spec.

Internally, ask-json uses ajv to validate data.

Use

CLI

Ask for data based on a JSON schema file.

$ askjson jsonSchema.json

Validate some data in a file. Answers to invalid or missing data will be rewritten to the file.

$ askjson jsonSchema.json -f data.json

Write validated data to a new file.

$ askjson jsonSchema.json -f data.json -o output.json
Module
import askJSON from 'ask-json';

const jsonSchema = {
  type: 'object',
  properties: {
    title: {
      type: 'string',
    },
    author: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
        },
        email: {
          type: 'string',
          format: 'email',
        },
      },
      required: ['name', 'email'],
    },
  },
  required: ['title', 'author'],
};

const rawData = {
  author: { name: 'Jon McClure' },
};

// Will ask user for title and author.email data!
const validData = await askJSON(jsonSchema, rawData);

Supported validation

As of the current version, ask-json handles simple schema validation rules and not all keywords are supported.

These are validation keywords currently handled by type:

  • number - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
  • string - maxLength, minLength, pattern, format
  • array - minItems, maxItems, items (object only!)
  • object - required, properties

Arrays in ask-json can only contain items of one type. For example, ask-json does not support this schema:

{
  "type": "array",
  "items": [
    { "type": "number" },
    { "type": "string" }
  ]
}

Because ask-json uses validation errors to trigger questions, any fields you want to prompt for when missing must be marked required. For example, in the following schema, ask-json will never ask for the email property unless it contains invalid data.

{
  "name": {
    "type": "string"
  },
  "email": {
    "type": "string",
    "format": "email"
  },
  "required": [
    "name"
  ]
}

Customizing questions

You can customize the questions used to ask users for missing or invalid data by adding a prompt property to your schema with prompts.js question options.

There are some conditions: You won't have access to the name property on your questions. Also, all functions will not have access to any previous answers -- e.g., (prev, values) => { ... }.

Lastly, the message property does not follow the usual signature in prompts.js. Instead, you can supply a string or a function which receives three params: the object dot-path of the variable being set, the validation error raised by ajv and the current value of the variable. If message is a string, you can use a chalk tagged template literal to add a bit of color to your message.

Here's an example of some custom prompts:

const schema = {
  type: 'object',
  email: {
    type: 'string',
    format: 'email',
    prompt: {
      message: (variablePath, error, currentValue) => {
        if(error.message) return `Your email "${currentValue}" is invalid: ${error.message}. What's your email?`;
        return `What's your email?`;
      }
    }
  }
  color: {
    type: 'string',
    prompt: {
      type: 'select',
      message: 'What {red color} do you want?',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' },
      ],
    },
  },
};

Asking to add additional items to an array

Outside fixing invalid and missing data, you can also prompt users to optionally add additional items to an array. Just pass a config object with askToAddItems set true:

const schema = {
  type: 'object',
  authors: {
    type: 'array',
    items: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        email: { type: 'string', format: 'email' },
      },
      required: ['name', 'email'],
    },
    minItems: 1,
    prompt: {
      // Can also use a custom message in the prompt to add items!
      addMessage: 'Would you like to add an additional {green author}?', 
    },
    maxItems: 5, // Won't prompt if array already has max items.
  },
  required: ['authors']
};

const rawData = {
  authors: [
    { name: 'Jon', email: '[email protected]' },
  ]
};

const config = { askToAddItems: true };

const validData = await askJSON(schema, rawData, config);

Testing

$ yarn build && yarn test

Some tests ask for manual input from the tester. You can skip these by running:

$ yarn build && yarn test-automatic-only