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 contentconst 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:
- Specify the JSON content to parse.
- And if that fails, specify a default value.
Using parseJSON
You can use parseJSON by first installing Splendid UI.
npm install splendidlabzThen 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 === defaultValueparseJSON is equivalent to the code I just wrote above:
// Parse JSON lets you write these 7 lines of code in a single linelet contentconst 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!