20

I have variable for example

var x = "this is X value";

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

3
  • 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. Commented Sep 4, 2012 at 12:09
  • 1
    I'm curious - why was the try/catch approach not an option? Commented Oct 25, 2016 at 15:53
  • This question is similar to: How to check if a string is a valid JSON string?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 30, 2024 at 6:06

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, I find here the answers stackoverflow.com/questions/3710204/…
this will not work if the string is a number, like JSON.parse(11) is 11 , no errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.