0

There are many sources on how to do so in Javascript, but it seems it's not that simple in Typescript. I want to check if a string is a valid JSON, I have tried the following code:

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

But no matter what string I try it does not throw an error, even a random string such as "[asc,22"

I have also tried this:

function testJSON(strJson) {
  try {
    const parsed = JSON.parse(strJson)
    if (parsed && typeof parsed === "object") {
      return true
    }
  } catch { return false }
  return false
}

But in this case it returns false no matter what string is used, I am not understanding why but the JSON.parse() function always returns a string no matter what I pass it.

I want the function to have results like this:

"123" => false
"abc" => false
"{ "prop_1": "val_1", "prop_2": "val_2" }" => true
"{ prop_1: "val_1", "prop_2": "val_2" }" => false

EDIT: This DOES work in Typescript after verifying on the online platform typescriptlang.org, I am not sure if it might be a problem in ReactJS, the file I am working in is of type .tsx

EDIT 2: The issue turned out not to be related to typescript or react, but the code was misusing elsewhere the "JSON.stringify" method, answer was posted below.

  • Does this answer your question? [How to test if a string is JSON or not?](https://stackoverflow.com/questions/9804777/how-to-test-if-a-string-is-json-or-not) – Wiktor Zychla Dec 16 '21 at 19:39
  • Your first function works fine. What is it exactly that you expect? – Jonathan Dec 16 '21 at 19:40
  • _"But no matter what string I try it does not throw an error"_ what error does it throw? If you click the "Run" button [here](https://tsplay.dev/mLLYam), it seems to work just fine. All I did was add the `: string` type annotation to your argument. – Alex Wayne Dec 16 '21 at 19:41
  • Turns out when I run the second function I mentioned in typescriptlang.org it does work according to what I need... But I cannot understand why it does not run in my code, I have now noticed that I did not mention I am working in ReactJS and the file type is .tsx and not .ts, I have no idea how this might have affected the result – Mariejoe Chahine Dec 16 '21 at 20:17

3 Answers3

1

It turned out that the second function I mentioned in the question is working afterall according to what I needed, what was happening is that deep in my code the input that was a string was being stringified again before being passed to the method, that meant that when I was parsing it, it was always returning a string and never throwing an error. My bad for not noticing the JSON.stringify and not understanding its behavior well.

The correct answer to this question would then be as mentioned in the question:

function testJSON(strJson) {
  try {
    const parsed = JSON.parse(strJson)
    if (parsed && typeof parsed === "object") {
      return true
    }
  } catch { return false }
  return false
}
0

JSON.parse() does throw an exception if the input is not correct, you are just catching it in the catch block, verify by running the snippet below.

console.log(JSON.parse("sqdfq["));
axtck
  • 3,707
  • 2
  • 10
  • 26
  • Turns out when I run it in typescriptlang.org it does work, but I cannot understand why it's not running in my code, I am using ReactJS and my file is a .tsx file. I will edit my question to mention that in case it has any effect – Mariejoe Chahine Dec 16 '21 at 20:19
0

You were correct but to show a good/bad example here it goes.

let badJSON = `'""{bad bad}"'"`;
let goodJSON = `{"type":"pong"}`;
let CheckJSON = (Data) => {
  try {
    let message = JSON.parse(Data);
    if (message.type == "pong") {
      console.log("PING");
    }
  } catch (e) {
    console.warn("close:");
  }
};
CheckJSON(goodJSON);
CheckJSON(badJSON);
https://stackoverflow.com/questions/70384627/check-if-a-string-is-a-valid-json-in-typescript#
BGPHiJACK
  • 1,277
  • 1
  • 8
  • 16
  • This does not work in my code, but I figured out it's not a problem in Typescript and updated my question, I am not sure if it's an issue with React and the tsx file type. When I try your function in my code, console.log(message.type) returns undefined, I have no idea why... – Mariejoe Chahine Dec 16 '21 at 20:27