How do I check if a string is a valid JSON in JavaScript?
Benjamin C
benjamin c profile pic

To check if a string is a valid JSON in JavaScript, you can use a try-catch block along with theJSON.parse() method. Here's an example of how you can validate a string as valid JSON:

1
2
3
4
5
6
7
8
9

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (error) {
    return false;
  }
}

In this example, theisValidJSON function takes a string,str, as input. It attempts to parse the string usingJSON.parse(). If the parsing is successful and no errors occur, it returnstrue, indicating that the string is valid JSON. If an error occurs during parsing, it catches the error and returnsfalse. Here's an example usage of theisValidJSON function:

1
2
3
4
5
6

const jsonString = '{"name": "John", "age": 30}';
const invalidString = '{"name": "John", age: 30}';

console.log(isValidJSON(jsonString)); // Output: true
console.log(isValidJSON(invalidString)); // Output: false

In this example, thejsonString variable contains a valid JSON string, whileinvalidString contains an invalid JSON string. TheisValidJSON function is called with both strings, and it returnstrue for the valid JSON andfalse for the invalid JSON. Keep in mind that this method checks if the string is valid JSON syntax. However, it does not guarantee that the JSON represents the expected structure or content. It's important to validate the JSON structure and properties according to your specific requirements if necessary. Note that in some cases, theJSON.parse() method can have performance implications for large strings or untrusted input. If performance or security is a concern, you may consider using a JSON validation library or implementing a more rigorous validation mechanism.