Validate JSON String Using JavaScript

May 22, 2018

1 min read

Published in

This article is for Validate JSON String using Javascript. It’s a JavaScript World, JavaScript is everywhere, on the browser, on the server, on mobile, on cloud and everyone uses JSON as data to pass from one end to other ends. JavaScript has an inbuilt function to parse the JSON object and which is supported by latest browsers. Before using JSON string, it has to be valid or it will throw an exception. Here is the function which validates the JSON string.

Validate JSON data using JavaScript Function.

1
2
3
4
5
6
7
8
function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

JSON.parse function will use string and converts to JSON object and if it parses invalidate JSON data, it throws an exception (“Uncaught SyntaxError: Unexpected string in JSON”).

Here is the example of Validate JSON Using Javascript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var validjsontext = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'; 

var invalidjsontext = '{"firstnam""James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'; 

console.log("With Valid JSON Text: "+IsValidJSONString(validjsontext));

console.log("With inValid JSON Text: "+IsValidJSONString(invalidjsontext));

function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

There are tools available online to check in detail JSON validation errors. Please visit these tools for test your JSON data.

https://jsonformatter.org

https://codebeautify.org/jsonvalidator

Are you also working with Python? try this Validate JSON Using Python.

Sharing is caring!