jsonrepair

repository·main·Indexed 25 days ago

https://github.com/josdejong/jsonrepair

A library for repairing invalid JSON documents, supporting a regular API for small files and a streaming API for large documents in Node.js. It fixes common syntax errors such as missing quotes around keys, trailing commas, single quotes, truncated JSON, and Python constants. The package includes a CLI tool for repairing files via the command line and supports usage in ES modules, CommonJS, UMD for browsers, and Python via PythonMonkey.

Tokens
2.9K
Snippets
10
Records
21
Agent score
80%

What's inside jsonrepair

  1. What issues can jsonrepair fix?

    main

    The library can repair a wide variety of common JSON syntax errors, including:

    • Missing quotes around keys
    • Missing escape characters
    • Missing commas
    • Missing closing brackets
    • Truncated JSON
    • Single quotes instead of double quotes
    • Special quote characters (e.g., “...”) replaced with regular double quotes
    • Special whitespace characters replaced with regular spaces
    • Python constants (None, True, False) replaced with null, true, and false
    • Trailing commas
    • Comments (/* ... */ and // ...)
    • Fenced code blocks (```json)
    • Ellipsis in arrays/objects ([1, 2, 3, ...])
    • JSONP notation (callback({ ... }))
    • Escaped strings (e.g., {"stringified": "content"})
    • MongoDB data types (NumberLong(2), ISODate(...))
    • Concatenated strings ("a" + "b")
    • Newline delimited JSON (converting multiple objects into a valid JSON array)
  2. Use jsonrepair in Python via PythonMonkey

    main

    You can use jsonrepair in Python by using the PythonMonkey library to bridge the npm package.

    import pythonmonkey
    
    jsonrepair = pythonmonkey.require('jsonrepair').jsonrepair
    
    json = "[1,2,3,"
    repaired = jsonrepair(json)
    print(repaired) 
    # [1,2,3]
  3. Configure jsonrepairTransform options

    main

    The jsonrepairTransform function accepts an optional configuration object to tune performance and memory usage:

    • chunkSize: Determines the size of the chunks that the transform outputs. Default is 65536 bytes. Increasing this can influence performance.
    • bufferSize: Determines how many bytes of the input and output stream are kept in memory as a "moving window". Default is 65536 bytes. Crucial: This must be larger than the length of the largest string and whitespace in the JSON data, otherwise an error is thrown. Increasing this improves reliability for large strings but increases memory usage.
    jsonrepairTransform(options?: { chunkSize?: number, bufferSize?: number }) : Transform
  4. Use the jsonrepair CLI to repair JSON files

    main

    The jsonrepair CLI tool allows you to repair invalid JSON documents via the command line. It supports reading from files or standard input (stdin) and writing to files or standard output (stdout).

    If a document cannot be repaired, the output will be left unchanged.

  5. Use jsonrepair in an ES module

    main

    Import the jsonrepair function to repair invalid JSON strings. The function returns a repaired JSON string or throws a JSONRepairError if it encounters an unfixable issue.

    import { jsonrepair } from 'jsonrepair'
    
    try {
      // The following is invalid JSON: keys are missing double quotes, 
      // and strings are using single quotes:
      const json = "{name: 'John'}"
      
      const repaired = jsonrepair(json)
      
      console.log(repaired) // '{"name": "John"}'
    } catch (err) {
      console.error(err)
    }
  6. Use jsonrepair in CommonJS

    main

    You can use jsonrepair in CommonJS environments, though it is not the recommended way to use the library.

    const { jsonrepair } = require('jsonrepair')
    const json = "{name: 'John'}"
    console.log(jsonrepair(json)) // '{"name": "John"}'
  7. Use jsonrepair via UMD in the browser

    main

    For browser-based usage, you can include the UMD build. Note that this is not the recommended method.

    <script src="/node_modules/jsonrepair/lib/umd/jsonrepair.js"></script>
    <script>
      const { jsonrepair } = JSONRepair
      const json = "{name: 'John'}"
      console.log(jsonrepair(json)) // '{"name": "John"}'
    </script>
  8. Use the Streaming API in Node.js

    main

    For handling infinitely large documents or processing data in a stream, use jsonrepairTransform from jsonrepair/stream. This is a Node.js Transform stream that can be used in a pipeline or via .pipe().

    import { createReadStream, createWriteStream } from 'node:fs'
    import { pipeline } from 'node:stream'
    import { jsonrepairTransform } from 'jsonrepair/stream'
    
    const inputStream = createReadStream('./data/broken.json')
    const outputStream = createWriteStream('./data/repaired.json')
    
    pipeline(inputStream, jsonrepairTransform(), outputStream, (err) => {
      if (err) {
        console.error(err)
      } else {
        console.log('done')
      }
    })
  9. Configure jsonrepairCore options

    main

    When initializing the streaming API with jsonrepairCore, you can provide the following configuration options:

    • onData: A callback function (chunk: string) => void that is invoked whenever a repaired chunk of JSON is ready.
    • chunkSize (optional): The size of the chunks emitted by the onData callback. Defaults to 65536.
    • bufferSize (optional): The size of the internal buffers used for processing. Defaults to 65536.
  10. Use the jsonrepair CLI

    main

    If installed globally via npm install -g jsonrepair, you can repair JSON files directly from the command line.

    Usage: jsonrepair [filename] {OPTIONS}

    Options:

    • --version, -v: Show application version
    • --help, -h: Show this message
    • --output, -o: Output file
    • --overwrite: Overwrite the input file
    • --buffer: Buffer size in bytes (e.g., 64K or 1M)

    Examples:

    $ jsonrepair broken.json                        # Repair a file, output to console
    $ jsonrepair broken.json > repaired.json        # Repair a file, output to file
    $ jsonrepair broken.json --output repaired.json # Repair a file, output to file
    $ jsonrepair broken.json --overwrite            # Repair a file, replace the file itself
    $ cat broken.json | jsonrepair                  # Repair data from an input stream
    $ cat broken.json | jsonrepair > repaired.json  # Repair data from an input stream, output to file
  11. Use jsonrepairTransform for Node.js streams

    main

    The jsonrepairTransform function creates a Node.js Transform stream that repairs JSON data as it flows through the stream. This is useful for processing large JSON files or network streams without loading the entire content into memory.

    It uses jsonrepairCore internally to handle the streaming logic. You can pass configuration options to control the internal buffering behavior.