How to check if a string is a valid JSON string?
To check if a string is valid JSON in JavaScript, simply wrap a call to JSON.parse()
inside a try..catch
block. A successful parse returns true
; an exception triggers the catch
block to return false
.
Options and pitfalls of validation
The standard method with try..catch
is certainly good, but at times you might need to validate JSON avoiding exceptions. Here's how:
Function without exceptions:
The regular expression in this code verifies the structure of the given string corresponds to JSON.
Checking parsed output:
This method involves parsing the string and checking the result type. Only objects and arrays represent valid JSON in JavaScript.
Catering to the specifics of JSON structure
Confirming an array of objects:
Above method is a double whammy. First, it checks if parsed JSON creates an array and for each object in the array, verifies if it is an object, matching our specific requirement.
Debugging scenarios in real world
At times, your debugger settings might lead to trouble with try..catch
blocks. Or you're one avoiding them in general. Fret not, alternatives exist.
Replace method approach:
Was this article helpful?