0

I want to validate a JSON object without the help of any libraries in nodejs.

user9052801
  • 53
  • 1
  • 6
  • 2
    Please define what do you mean by `validate` and post a sample json – AbhinavD May 07 '18 at 09:32
  • And what did you find so far and why it doesn't fit your needs? – ChrisR May 07 '18 at 09:32
  • I just want to know if the JSON object is valid without errors. there are a lot of libraries which does the job I want to do it without using them. – user9052801 May 07 '18 at 09:35
  • i just want to check if the json objcet passed is without errors and in proper syntax. – user9052801 May 07 '18 at 09:36
  • Just use [JSON.prase](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). It will throw error if invalid json. Look at the link provided by @ChrisR – AbhinavD May 07 '18 at 09:37

1 Answers1

3

Just by parsing it, using JSON.parse function:

function isValidJSON(text){
    try{
        JSON.parse(text);
        return true;
    }
    catch (error){
        return false;
    }
}


console.log(isValidJSON("hello")); // false
console.log(isValidJSON("{}")); // true
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53