shas
shas

Reputation: 703

How to validate json data in javascript

Am reading file and storing content in one variable ie var json.

suppose variable contains like this

var json = {
    "abc":"abc",
    "xyz":"xyz"
}

Above variable contains valid json.

If there is an error happen in Json file, is there a way to find out where the error is, e.g. line number and column number?

like this if it is invalid

var json1 = {
"abc":"abc",
"xyz":xyz"
}

The error should show like this

Parse error on line 3:
...: "abc",    "xyz": xyz"}
----------------------^

Upvotes: 0

Views: 9858

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075427

You don't have any JSON in your question, but if we assume you do:

var json = '{ "abc":"abc", "xyz":"xyz" }';

All modern browsers support JSON.parse, which will throw an exception if the JSON is invalid, so:

try {
    var obj = JSON.parse(json);
}
catch (e) {
    // The JSON was invalid, `e` has some further information
}

Those won't give you line and column, though. To do that, you may need a parsing script. Before browsers had JSON.parse built in, there were scripts like Crockford's json2.js and various others listed at the bottom of the JSON.org page that may give you line and character info (or can be modified to).

JSON.parse example:

var valid = '{ "abc":"abc", "xyz":"xyz" }';
test("valid", valid);

var invalid = '{ "abc", "xyz":xyz }';
test("invalid", invalid);

function test(label, json) {
  try {
    JSON.parse(json);
    snippet.log(label + ": JSON is okay");
  }
  catch (e) {
    snippet.log(label + ": JSON is malformed: " + e.message);
  }
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 6

Related Questions