or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-json

A fast command-line interface tool for working with JSON data, designed as a single-file Node.js script with no external dependencies.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/json@11.0.x

To install, run

npx @tessl/cli install tessl/npm-json@11.0.0

index.mddocs/

JSON

JSON is a fast command-line interface tool for working with JSON data, designed as a single-file Node.js script with no external dependencies. It enables users to pretty-print JSON, extract specific values using natural JavaScript-like syntax, validate JSON syntax with detailed error reporting, filter and transform JSON data through inline expressions, and process streaming JSON data efficiently.

Package Information

  • Package Name: json
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install -g json
  • Binary: json command

Core Imports

For module usage (limited API):

const json = require('json');

ES modules (if supported):

import * as json from 'json';

Basic Usage

Command Line Interface (Primary Usage)

# Pretty-print JSON
echo '{"name":"trent","age":38}' | json
# {
#   "name": "trent", 
#   "age": 38
# }

# Extract specific values
echo '{"name":"trent","age":38}' | json name
# trent

# Filter and transform data
echo '[{"age":38},{"age":4}]' | json -c 'this.age > 21'
# [{"age":38}]

# Process array with tabular output
echo '[{"name":"trent","age":38},{"name":"ewan","age":4}]' | json -a name age
# trent 38
# ewan 4

Module Usage (Limited)

const json = require('json');

// Get version
console.log(json.getVersion()); // "11.0.0"

// Parse lookup expressions
const lookup = json.parseLookup('user.name');
console.log(lookup); // ['user', 'name']

// Apply lookups to data
const data = { user: { name: 'Alice' } };
const result = json.lookupDatum(data, lookup);
console.log(result); // 'Alice'

Capabilities

Command Line Processing

The primary interface is the json command which processes JSON data from stdin or files.

json [OPTIONS] [LOOKUPS...]
json -f FILE [OPTIONS] [LOOKUPS...]

Core Command Line Options:

# Input/Output Options
-f FILE              # Specify input file (instead of stdin)
-I, --in-place       # Edit file in-place (requires -f FILE)
-q, --quiet          # Don't warn if input isn't valid JSON

# Processing Options  
-H                   # Drop HTTP header blocks
-g, --group          # Group adjacent objects/arrays
--merge              # Merge adjacent objects (shallow)
--deep-merge         # Merge adjacent objects (deep)
-M, --items          # Itemize object into key/value pairs
-a, --array          # Process as array with tabular output
-A                   # Process as single object (override array processing)

# Filtering and Execution Options
-e CODE              # Execute JavaScript code on input
-c CODE              # Filter input with JavaScript condition
-k, --keys           # Output object keys
-n, --validate       # Just validate JSON (no output)

# Output Format Options
-o MODE, --output MODE # Output mode (jsony, json, inspect, compact)
-i                   # Shortcut for -o inspect
-j                   # Shortcut for -o json
-0, -2, -4          # Set indentation level
-d DELIM            # Delimiter for tabular output

# Lookup Options
-D DELIM            # Delimiter for lookups (default: '.')

# Help Options
-h, --help          # Print help
--version           # Print version

JSON Processing Features

Core JSON processing capabilities available via command line.

Pretty Printing:

  • Default "jsony" output: JSON with unquoted single strings
  • Pure JSON output with configurable indentation
  • Node.js util.inspect format with colors
  • Compact experimental format

Data Extraction:

  • Dot notation lookups: field.subfield
  • Array indexing: array.0 or array[0]
  • Negative array indexing: array.-1 (Python-style)
  • Bracket notation for complex keys: ["field.with.dots"]
  • Custom lookup delimiters

Data Transformation:

  • JavaScript code execution with -e option
  • Conditional filtering with -c option
  • Object key extraction with -k
  • Array processing with tabular output using -a

Advanced Processing:

  • HTTP header stripping for REST API responses
  • Object grouping and array concatenation
  • Object merging (shallow and deep)
  • Key-value itemization for objects
  • Streaming support for large files

Validation and Error Handling

JSON validation with detailed error reporting.

# Validate JSON with detailed errors
json -n, --validate   # Just validate, no output
json -q              # Quiet mode for silent validation

Error Reporting Features:

  • Line and column position for syntax errors
  • Context highlighting with error markers
  • Graceful handling of non-JSON input
  • HTTP header detection and processing

Module API (Limited)

The package provides a limited module API for programmatic access.

/**
 * Main entry point function that processes command line arguments
 * @param {string[]} argv - Command line arguments array
 */
function main(argv);

/**
 * Returns the version string
 * @returns {string} Version number
 */
function getVersion();

/**
 * Parse lookup string into array of lookup components
 * @param {string} lookup - The lookup expression (e.g., "user.name")
 * @param {string} [lookupDelim='.'] - Optional delimiter character (default: '.')
 * @returns {Array<string|number>} Array of lookup components
 */
function parseLookup(lookup, lookupDelim);

/**
 * Apply a parsed lookup to data object
 * @param {*} datum - The data to lookup from
 * @param {Array<string|number>} lookup - Parsed lookup array from parseLookup()
 * @returns {*} The result of the lookup, or undefined if not found
 */
function lookupDatum(datum, lookup);

/**
 * Print datum with formatting options (DEPRECATED - use stringifyDatum instead)
 * @param {*} datum - Data to print
 * @param {object} opts - Output options
 * @param {string} sep - Separator string
 * @param {boolean} alwaysPrintSep - Always print separator flag
 * @deprecated This function is deprecated in favor of other output methods
 */
function printDatum(datum, opts, sep, alwaysPrintSep);

Lookup System

Powerful lookup system for extracting data from JSON structures.

Lookup Syntax:

  • Dot notation: user.profile.name
  • Array indexing: users.0.name or users[0].name
  • Negative indexing: users.-1 (last element)
  • Bracket notation: ["field.with.dots"] or ['field-with-hyphens']
  • Custom delimiters: -D/ allows user/profile/name

Special Cases:

  • Negative array indices for Python-style access
  • Quoted strings for complex property names
  • Mixed notation: users[0].profile["display-name"]

Stream Processing

Efficient processing of large JSON files and streams.

# Stream processing with grouping and array output
json -ga [LOOKUPS...]   # Group + array processing for streaming

# Process multiple files
cat *.json | json -g [OPTIONS] [LOOKUPS...]

Streaming Features:

  • Automatic object/array grouping for concatenated JSON
  • Memory-efficient processing of large files
  • Support for newline-separated JSON objects (like log files)
  • HTTP header detection in streams

Environment Variables

Configuration through environment variables.

JSON_EXEC=vm    # Use legacy vm execution mode for -e/-c options

Types

// Output mode constants
const OM_JSONY = 1;     // Default "jsony" output mode
const OM_JSON = 2;      // Pure JSON output mode  
const OM_INSPECT = 3;   // Node.js util.inspect output mode
const OM_COMPACT = 4;   // Compact output mode

// Output mode mapping
const OM_FROM_NAME = {
  'jsony': OM_JSONY,
  'json': OM_JSON,
  'inspect': OM_INSPECT,
  'compact': OM_COMPACT
};

// Options object structure (internal)
/**
 * @typedef {Object} ParsedOptions
 * @property {string[]} args - Remaining command line arguments
 * @property {boolean} help - Help flag
 * @property {boolean} quiet - Quiet mode flag
 * @property {boolean} dropHeaders - Drop HTTP headers flag
 * @property {string[]} exeSnippets - JavaScript execution snippets from -e
 * @property {string[]} condSnippets - JavaScript condition snippets from -c
 * @property {number} outputMode - Output mode (OM_JSONY, OM_JSON, etc.)
 * @property {number|string} jsonIndent - JSON indentation (number of spaces or '\t' for tab)
 * @property {boolean|null} array - Array processing flag (null = auto-detect)
 * @property {string} delim - Delimiter for tabular output (default: ' ')
 * @property {string} lookupDelim - Delimiter for lookup parsing (default: '.')
 * @property {boolean} items - Itemize objects into key-value pairs flag
 * @property {boolean} outputKeys - Output object keys flag
 * @property {boolean} group - Group adjacent objects/arrays flag
 * @property {string|null} merge - Merge mode ('shallow', 'deep', or null)
 * @property {string[]} inputFiles - Input file paths from -f options
 * @property {boolean} validate - Validation-only mode flag
 * @property {boolean} inPlace - In-place editing flag
 */

Installation Examples

Global installation for CLI usage:

npm install -g json

Manual installation:

cd ~/bin
curl -L https://github.com/trentm/json/raw/master/lib/json.js > json
chmod 755 json

Module usage in package.json:

{
  "dependencies": {
    "json": "^11.0.0"
  }
}

Usage Examples

REST API Processing:

# Pretty-print API response
curl -s https://api.github.com/repos/user/repo | json

# Extract specific fields
curl -s https://api.github.com/repos/user/repo | json name description

# Filter with conditions
curl -s https://api.github.com/repos/user/repo/issues | json -c 'this.state === "open"'

File Processing:

# Format JSON file
json -f config.json

# In-place editing
json -I -f config.json -e 'this.port = 8080'

# Extract configuration values
json -f package.json version scripts.start

Data Analysis:

# Tabular output from array
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | json -a name age

# Get object keys
echo '{"a":1,"b":2,"c":3}' | json -k

# Process log files
cat app.log | json -ga timestamp level message

Advanced Processing:

# Object itemization for key-value processing
echo '{"users":{"alice":{"age":30},"bob":{"age":25}}}' | json users -M -a key value.age

# Merging configuration files
cat base.json override.json | json --merge

# Validation with detailed errors
cat invalid.json | json -n