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.

l2mt
  • 550
  • 2
  • 7
  • 20
  • 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 Jan 19 '14 at 14:38

1 Answers1

-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;
}
Pavlo
  • 43,301
  • 14
  • 77
  • 113
  • 7
    He said using regex. why do you answer with _Instead of using RegEx_ ? why? – Royi Namir Jan 19 '14 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 Jan 19 '14 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 Jan 19 '14 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 Jan 19 '14 at 17:33