admin管理员组

文章数量:1394067

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"}
----------------------^

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"}
----------------------^
Share Improve this question edited Feb 29, 2016 at 12:13 shas asked Mar 4, 2015 at 9:34 shasshas 7032 gold badges9 silver badges31 bronze badges 3
  • "This is valid json file" No, that's a valid JavaScript object initializer, within an assignment statement, bined with a var statement. No JSON here. – T.J. Crowder Commented Mar 4, 2015 at 9:37
  • Actually, it's an invalid object initializer: You're missing the " after the xyz property name. – T.J. Crowder Commented Mar 4, 2015 at 9:42
  • Your invalid JSON will give JavaScript error right away with line number, in your console – Bikas Commented Sep 8, 2015 at 12:37
Add a ment  | 

1 Answer 1

Reset to default 6

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 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./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

本文标签: How to validate json data in javascriptStack Overflow