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-parseror with pnpm:
pnpm add typed-json-parseror 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: trueHandling 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 testTo run in watch mode:
pnpm test:watch🛠️ Development
- Clone the repository
- Install dependencies:
pnpm install - Run tests:
pnpm test - Build:
pnpm build
🤝 Contributing
Contributions are welcome! Please:
- Fork the project
- Create a feature branch (
git checkout -b feature/new-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/new-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License.
👥 Authors
- Peterson Pereira Bozza - [email protected]
- Guilherme Saliba - [email protected]
Made with ❤️ for the JavaScript/TypeScript community
