Share via

How to validate JSON in JavaScript?

Avinash verma 0 Reputation points
2025-12-23T10:58:07.8866667+00:00

I am working with JavaScript and receiving JSON data from an API.

Before parsing the response, I want to check whether the JSON is valid

to avoid runtime errors.

What is the recommended way to validate JSON in JavaScript?

Are there any best practices for handling invalid JSON gracefully?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

3 answers

Sort by: Most helpful
  1. Surya Amrutha Vaishnavi Lanka (INFOSYS LIMITED) 2,115 Reputation points Microsoft External Staff
    2025-12-24T11:44:36.3066667+00:00

    Thanks for sharing the details!

    Try-Catch Block: You can wrap your JSON parsing logic in a try-catch block. If the JSON is not valid, it will throw an error that you can handle gracefully. Here's an example:

    function validateJSON(jsonString) {
        try {
            JSON.parse(jsonString);
            return true; // Valid JSON
        } catch (e) {
            console.error("Invalid JSON:", e);
            return false; // Invalid JSON
        }
    }
    
    const jsonData = '{"name": "John", "age": 30}'; // Example JSON string
    
    if (validateJSON(jsonData)) {
        console.log("JSON is valid!");
        // Proceed with your logic
    } else {
        console.log("JSON is invalid. Handle the error gracefully.");
    }
    
    1 person found this answer helpful.

  2. Q&A Assist
    2025-12-23T10:58:18.26+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To validate JSON in JavaScript, you can use a try-catch block with the JSON.parse() method. This method attempts to parse a JSON string, and if the string is not valid JSON, it will throw an error. Here's an example:

    function validateJSON(jsonString) {
        try {
            JSON.parse(jsonString);
            return true; // Valid JSON
        } catch (e) {
            return false; // Invalid JSON
        }
    }
    
    const jsonData = '{"name": "John", "age": 30}';
    console.log(validateJSON(jsonData)); // true
    
    const invalidJsonData = '{name: "John", age: 30}';
    console.log(validateJSON(invalidJsonData)); // false
    

    Best Practices for Handling Invalid JSON Gracefully:

    1. Use Try-Catch: Always wrap your JSON parsing in a try-catch block to handle any potential errors gracefully.
    2. Log Errors: If parsing fails, log the error to help diagnose issues with the JSON structure.
    3. User Feedback: Provide user feedback if the JSON is invalid, such as displaying an error message or a fallback UI.
    4. Default Values: Consider using default values or fallback mechanisms in case of invalid JSON to ensure your application continues to function smoothly.
    5. Schema Validation: For more complex JSON structures, consider using a JSON schema validator to ensure the data adheres to expected formats before parsing.

    By following these practices, you can effectively manage JSON data and minimize runtime errors in your JavaScript applications.

    1 person found this answer helpful.
  3. Bruce (SqlWork.com) 83,821 Reputation points
    2025-12-24T17:25:52.1533333+00:00

    If you want to validate the schema, then ajv is the most popular

    https://ajv.js.org

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.