ZL
About Articles Contact
Published on Oct 31, 2023
Filed under:
#splendidlabz,
#javascript

Easy way to parse JSON with JavaScript

When you use JSON.parse to parse JSON, you almost always need to make sure you pass in a JSON value, so you will end up having to use a try/catch block most of the time.

try {
const content = JSON.parse(someValue)
} catch (e) {
// Handle the error
}

Most of the time, you’ll want to set a default value when the parsing fails. So the code ends up looking like this:

let content
const defaultValue = {} // Change this to any other value
try {
content = JSON.parse(json)
} catch (e) {
content = defaultvalue
}

I think this process can be simplified so I created a helper function, parseJSON that lets you do these two things in a single line:

  1. Specify the JSON content to parse.
  2. And if that fails, specify a default value.

Using parseJSON

You can use parseJSON by first installing Splendid UI.

Terminal window
npm install splendidlabz

Then import it into your project:

import { parseJSON } from 'splendidlabz/utils'

Here’s how you can use parseJSON.

const value = parseJSON(json, defaultValue)
// If JSON is valid value will be === JSON data
// If JSON is invalid, value will be === defaultValue

parseJSON is equivalent to the code I just wrote above:

// Parse JSON lets you write these 7 lines of code in a single line
let content
const defaultValue = {}
try {
content = JSON.parse(json)
} catch (e) {
content = defaultvalue
}

Since parseJSON is a Vanilla JavaScript utility, you can use it anywhere — frontend JavaScript, Node, and even in frameworks!

That’s all you have to know about parseJSON!

Take it out for a spin and let me know what you think!

Further reading

  • Splendid UI
  • parseJSON documentation
Previous Splendid Layouts in here! Next An easy way to implement conversion tracking for Facebook

Join My Newsletter

I share what I’m learning on this newsletter: code, building businesses, and living well.

Sometimes I write about technical deep-dives, product updates, musings on how to live, and sometimes my struggles and how I’m breaking through.

Regardless of the type of content, I do my best to send you an update every week.

If you’re into making things and growing as a person, you’ll probably feel at home here.

“

Zell is one of those rare people who commands tremendous knowledge and experience but remains humble and helpful. They want you to know what they know, not just be impressed by it.

In other words, Zell is a natural teacher. You’re lucky to have him because he feels lucky to be able to help you in your journey.

Heydon Pickering
Heydon Pickering — Web & Accessibility Extraordinaire
The Footer

General

Home About Contact Testimonials Tools I Use

Projects

Magical Dev School Splendid Labz

Socials

Youtube Instagram Tiktok Github Bluesky X

Follow Along

Email RSS
© 2013 - 2025 Zell Liew / All rights reserved / Terms