Explain Codes LogoExplain Codes Logo

How to test if a string is JSON or not?

javascript
json-parsing
error-handling
javascript-functions
Nikita BarsukovbyNikita Barsukov·Sep 7, 2024
TLDR

You can validate if a string is JSON by weaving JSON.parse() into a try-catch block. A successful execution counts as JSON, while a failure indicates otherwise. Here's your magic wand:

const isJSON = str => { try { JSON.parse(str); return true; // You're in JSON land now! } catch (e) { return false; // Not today JSON, not today. } }; // Initiating testing protocols console.log(isJSON('{"valid":true}')); // true console.log(isJSON('Invalid string')); // false

Crafting a better mousetrap: Enhancing parsing precision

To improve accuracy and reliability you can consider the response's content-type or inspect responseJSON in AJAX calls. This allows you to distinguish between JSON and error messages, significantly enhancing user experience. Like a door bouncer, checking IDs before letting AJAX responses into JSON club.

False positives: handle with care

A simple isJSON check can sometimes act overenthusiastic leading to false positives. For instance, passing JSON.parse("true") would return true, which might make you 😔, if you're just expecting JSON objects or arrays. Let’s tighten up the rules:

const hasJsonStructure = str => { if (typeof str !== 'string') return false; try { const result = JSON.parse(str); const type = Object.prototype.toString.call(result); return type === '[object Object]' || type === '[object Array]'; // Object or Array is our VIP } catch (e) { return false; // You get a “not today" } }; // Testing different scenarios like a pro console.log(hasJsonStructure('{"valid":true}')); // true console.log(hasJsonStructure('[]')); // true console.log(hasJsonStructure('"true"')); // false, you thought I'd let it through, huh? console.log(hasJsonStructure('null')); // false console.log(hasJsonStructure('Invalid string')); // false

Handling errors and user feedback

Implementing a safeJsonParse function ensures gracious error handling and provides valuable feedback:

const safeJsonParse = (str) => { try { return [null, JSON.parse(str)]; } catch (e) { return [e.message, null]; // Classy move, a parting gift for our gracious loser. } }; // Usage const [error, value] = safeJsonParse('Invalid string'); console.log(error); // SyntaxError: Unexpected token I in JSON at position 0 console.log(value); // null

Testing robustness: kick the tires

Hit your isJSON function with different input types. This is like giving your function a full body workout 💪:

  • Different data types like string, number, null, undefined.
  • Complex JSON objects and arrays, the deeper the better.
  • The oddballs like empty JSON objects {} and arrays [].
  • Your common mischief makers, with syntax violations or malformed structures.
  • The wolves in sheep’s clothing. Strings appearing JSON but missing critical syntax.