1

I receive in my system from a textbox the following JSON String format and I like to know if there is a way of validate with a regexp that is a valid JSON string:

{
  "settings":{
    "user":"...",
    "pass":"..."
  },
  "data":[
    {
      "id":1,
      "field1":"...",
      "field2":"..."
    },
    {
      "id":2,
      "field1":"...",
      "field2":"..."
    }
  ]
}

Thanks for any suggestion.

1
  • simply validating that something is json is pretty lame in that it tells you nothing about the data. it's like decalring a whole form valid because one textbox is not blank. it's much safer and more reliable to parse and validate the actual data instead of just saying "it looks like it's the shape of something that could be what i want"...
    – dandavis
    Commented Jan 19, 2014 at 14:38

1 Answer 1

-5

Instead of using RegEx you could try to parse it straight away:

function isValidJSON(string) {
  try {
    JSON.parse(string);
  } catch (e) {
    return false;
  }

  return true;
}
4
  • 7
    He said using regex. why do you answer with Instead of using RegEx ? why?
    – Royi Namir
    Commented Jan 19, 2014 at 14:33
  • 2
    @RoyiNamir OP also didn't state he anything about try/catch. I believe that regex would be an overkill for the task. Is my answer not useful?
    – Pavlo
    Commented Jan 19, 2014 at 14:38
  • 1
    he said using regex. Also , JSON is not supported under ie8. Also , he should have google that - it's duplicate.
    – Royi Namir
    Commented Jan 19, 2014 at 14:39
  • 1
    I'm new in this scenario, so an answer that solve my problem it's good,although it's not what I was expecting.
    – l2mt
    Commented Jan 19, 2014 at 17:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.