20

I have variable for example

var x = "this is X value";

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

JohnnyHK
  • 290,447
  • 61
  • 595
  • 453
prilia
  • 956
  • 5
  • 17
  • 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

54

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
  • 15,618
  • 15
  • 60
  • 77
  • 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