20

I have variable for example

var x = "this is X value";

How to check in node.js if variable is JSON object ?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
prilia
  • 996
  • 5
  • 18
  • 41
  • 1
    If you expect JSON input, you should use `JSON.parse`. Surround it will `try { ... } catch { ... }`. If there is an exception, it was not valid JSON input. – Linus Thiel Sep 04 '12 at 12:09
  • 1
    I'm curious - why was the try/catch approach not an option? – niczak Oct 25 '16 at 15:53

1 Answers1

55

Your question is not clear, but assuming you meant to check if a variable has an unparsed JSON string:

try {
    JSON.parse(x);
} catch (e) {
    console.log("not JSON");
}
Mahn
  • 16,261
  • 16
  • 62
  • 78
  • thank you, I find here the answers http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try – prilia Sep 04 '12 at 12:32
  • this will not work if the string is a number, like JSON.parse(11) is 11 , no errors – Ishaan Sharma Mar 26 '23 at 12:26