HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to check if a string is a valid JSON string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcheckvalidstringjson

Problem

isJsonString('{ "Id": 1, "Name": "Coke" }')


should be true and

isJsonString('foo')
isJsonString('foo')


should be false.

I'm looking for a solution that doesn't use try/catch because I have my debugger set to "break on all errors" and that causes it to break on invalid JSON strings.

Solution

A comment first. The question was about not using try/catch.

If you do not mind to use it, read the answer below.
Here we just check a JSON string using a regexp, and it will work in most cases, not all cases.

Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js

There is a regexp that check for a valid JSON, something like:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

  //the json is ok

}else{

  //the json is not ok

}


EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )

Code Snippets

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

  //the json is ok

}else{

  //the json is not ok

}

Context

Stack Overflow Q#3710204, score: 214

Revisions (0)

No revisions yet.