Chi Chan Chi Chan - 1 year ago 200
JSON Question

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

Something like:

var jsonString = '{ "Id": 1, "Name": "Coke" }';

//should be true

//should be false

The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.

Mic Mic
Answer Source

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

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


  //the json is not ok

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download