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 🙏

© 2025 – Pkg Stats / Ryan Hefner

typed-json-parser

v0.0.6

Published

A TypeScript wrapper around JSON.parse that returns {data, error} instead of throwing exceptions, following Go's error handling pattern

Readme

Typed JSON Parser

A TypeScript wrapper around JSON.parse that returns {data, error} instead of throwing exceptions, following Go's error handling pattern.

📋 About

typed-json-parser is a library that provides a safer alternative to JavaScript's native JSON.parse. Instead of throwing exceptions when encountering malformed JSON, the function returns an object with data and error fields, allowing for more explicit and predictable error handling.

🚀 Installation

npm install typed-json-parser

or with pnpm:

pnpm add typed-json-parser

or with yarn:

yarn add typed-json-parser

🛠️ Usage

Import

import { parseJSON } from 'typed-json-parser'

Basic Usage

// Valid JSON
const { data, error } = parseJSON('{"name": "John", "age": 30}')

if (error) {
  console.error('Error parsing JSON:', error.message)
} else {
  console.log('Data:', data) // { name: "John", age: 30 }
}

// Invalid JSON
const { data: invalidData, error: invalidError } = parseJSON('{"name": "John", age: 30}') // missing quotes around age

if (invalidError) {
  console.error('Malformed JSON:', invalidError.message)
} else {
  console.log('Data:', invalidData)
}

Comparison with Traditional JSON.parse

Traditional Approach (with try/catch):

try {
  const data = JSON.parse(jsonString)
  // use data
} catch (error) {
  // handle error
  console.error('Error:', error)
}

With typed-json-parser:

const { data, error } = parseJSON(jsonString)

if (error) {
  // handle error
  console.error('Error:', error)
} else {
  // use data
}

📚 API

parseJSON(jsonString: string): ParseResult

Parses a JSON string and returns an object with data or error.

Parameters

  • jsonString (string): The JSON string to be parsed

Returns

The function returns an object of type ParseResult which can be:

type ParseResult =
  | {
      data: any;
      error: null;
    }
  | {
      data: null;
      error: Error;
    };
  • Success: { data: any, error: null } - contains the parsed data
  • Error: { data: null, error: Error } - contains the error that occurred

Usage Examples

Parsing Objects:

const { data, error } = parseJSON('{"user": "maria", "active": true}')
// data: { user: "maria", active: true }

Parsing Arrays:

const { data, error } = parseJSON('[1, 2, 3, "test"]')
// data: [1, 2, 3, "test"]

Parsing Primitive Values:

const { data, error } = parseJSON('"hello world"')
// data: "hello world"

const { data, error } = parseJSON('42')
// data: 42

const { data, error } = parseJSON('true')
// data: true

Handling Errors:

const { data, error } = parseJSON('{"malformed": }')
// error: SyntaxError: Unexpected token } in JSON at position...
// data: null

🎯 Use Cases

1. API Input Validation

function processRequest(body: string) {
  const { data, error } = parseJSON(body)
  
  if (error) {
    return { status: 400, message: 'Invalid JSON' }
  }
  
  // Process valid data
  return { status: 200, data }
}

2. Application Configuration

function loadConfig(configString: string) {
  const { data: config, error } = parseJSON(configString)
  
  if (error) {
    console.warn('Using default configuration due to error:', error.message)
    return DEFAULT_CONFIG
  }
  
  return { ...DEFAULT_CONFIG, ...config }
}

3. Batch Data Processing

function processBatchJSON(jsonStrings: string[]) {
  return jsonStrings.map(jsonStr => {
    const { data, error } = parseJSON(jsonStr)
    
    return {
      original: jsonStr,
      parsed: data,
      success: !error,
      error: error?.message
    }
  })
}

🔄 Advantages

  • No Exceptions: Doesn't throw exceptions, making control flow easier
  • Type Safety: Explicit types for success and error cases
  • Go Pattern: Follows Go's familiar error handling pattern
  • Simplicity: Simple and intuitive API
  • Compatibility: Works with any valid JSON supported by JSON.parse

🧪 Testing

Run tests with:

pnpm test

To run in watch mode:

pnpm test:watch

🛠️ Development

  1. Clone the repository
  2. Install dependencies: pnpm install
  3. Run tests: pnpm test
  4. Build: pnpm build

🤝 Contributing

Contributions are welcome! Please:

  1. Fork the project
  2. Create a feature branch (git checkout -b feature/new-feature)
  3. Commit your changes (git commit -am 'Add new feature')
  4. Push to the branch (git push origin feature/new-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License.

👥 Authors

Made with ❤️ for the JavaScript/TypeScript community