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

tryjson

v1.1.4

Published

Try to parse a string as JSON and return undefined on failure

Downloads

162

Readme

node tryjson

npm install Build Status Dependencies Status Known Vulnerabilities Downloads License

TL;DR

JSON.parse / JSON.stringify

// this can crash your program
// you need try/catch:
object = JSON.parse(string);

// this can crash your program
// you need try/catch:
string = JSON.stringify(object);

tryjson.parse / tryjson.stringify

// no need for try/catch:
string = tryjson.stringify(object);

// no need for try/catch:
object = tryjson.parse(string);

Why

Not everyone knows that you should always run JSON.parse inside of a try/catch block or otherwise you risk your application crashing on bad input. Most of the examples of using JSON.parse posted online never does that. People usually assume that you will get undefined on bad or empty input but you don't.

Remember: Always try { JSON.parse() } or use tryjson.parse()

This module works like many people assume that the built-in JSON works and can simplify some common code.

People usually write:

object = JSON.parse(string);

when they mean:

try {
  object = JSON.parse(string);
} catch (e) {
  object = undefined;
}

and now they can write it as:

object = tryjson.parse(string);

or even as:

object = JSON.parse(string);

if you want to locally override JSON with:

var JSON = require('tryjson');

You can even get a different value than the default undefined for invalid JSON:

object = JSON.parse(string, {error: 'Invalid JSON'});

How it works

This module works like JSON.parse (and in fact it uses JSON.parse) but instead of throwing exceptions it returns undefined on failure (or some other fallback value if provided). This is not always a desired behaviour but sometimes it is.

There is also a stringify method that works like JSON.stringify but instead of throwing exceptions on circular structures it returns "null" (or a JSON representation of some other fallback value if provided) - which, again, may not be what you always want but sometime it is and you can use this module to simplify your code in those cases.

Methods

parse(string)

Returns the result of parsing string as JSON or undefined if it cannot be parsed.

parse(string, fallback)

Returns the result of parsing string as JSON or the value of fallback if it cannot be parsed.

stringify(value)

Returns the JSON representation of value or the JSON representation of null if value cannot be represented as JSON (e.g. contains circular references).

stringify(value, fallback)

Returns the JSON representation of value or the JSON representation of fallback if value cannot be represented as JSON (or the JSON representation of null if fallback cannot be represented as JSON as well).

Rationale

Why tryjson.parse returns undefined for invalid JSON by default? Because a valid JSON can never be parsed to undefined so you can test it reliably for that value with value === undefined to know if it was invalid. You can specify a custom fallback value as a second argument.

Why tryjson.stringify returns "null" for objects that cannot be serialized by default? Because "null" is a valid JSON string so it can always be parsed without errors and is still easy to test for null value. Note that this time, getting "null" does not necessarily mean that the object couldn't be serialized because it might have been originally equal to null as well. You can specify a custom fallback value as a second argument - it will be stringified to JSON if possible, or the string "null" will be returned. It always returns a valid JSON string.

Installation

Install to use in your Node project, updating the dependencies in package.json:

npm install tryjson --save

Examples

Basic usage:

Parsing

var tryjson = require('tryjson');

tryjson.parse('{"a":1,"b":2}');
// returns object: { a: 1, b: 2 }

tryjson.parse('{"a":1,"b":2');
// returns value: undefined

Stringification

var tryjson = require('tryjson');

var x = {a: 1};
tryjson.stringify(x);
// returns string: '{"a":1}'
x.b = x;
tryjson.stringify(x);
// returns string: 'null'

Testing returned values

var object = tryjson.parse(string);

if (object === undefined) {
  // the string was invalid JSON
}

if (object == null) {
  // the string was either invalid JSON
  // or "null"
}

if (!object) {
  // the string was either invalid JSON,//
  // "null", "false" or "0"
}

Custom fallback values:

tryjson.parse('{"a":1,"b":2}', {err: 'bad json'});
// returns object: { a: 1, b: 2 }

tryjson.parse('{"a":1,"b":2', {err: 'bad json'});
// returns object: { err: 'bad json' }

var x = {a: 1};
tryjson.stringify(x, {err: 'bad object'});
// returns string: '{"a":1}'
x.b = x;
tryjson.stringify(x, {err: 'bad object'});
// returns string: '{"err":"bad object"}'

// invalid object and invalid fallback:
tryjson.stringify(x, x);
// returns string: 'null'

Issues

For any bug reports or feature requests please post an issue on GitHub.

Author

Rafał Pocztarski - https://github.com/rsp

License

MIT License (Expat). See LICENSE.md for details.