Eric Herlitz
Eric Herlitz

Reputation: 26307

Using regex to validate JSON in JavaScript

I got a simple JSON that could benefit from some regex testing

{
    "Name": "Ingemar Stenmark",
    "personalNumber": "197304211770",
    "id": "069234f2-771c-415a-aa5a-3ca77c74f832"
}

It would be formatted like that exempt no line breaks ({"Name": "Ingemar Stenmark", "personalNumber": "197304211770", "id": "069234f2-771c-415a-aa5a-3ca77c74f832"})

Is there any way it could be tested in js using regex?

Upvotes: 0

Views: 186

Answers (1)

adrum
adrum

Reputation: 71

It would need to be a string for you to run a regex test on it.

But once it's a string you can create a regex using the js global RegExp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp and use the RegExp test method:

const json = {
    "Name": "Ingemar Stenmark",
    "personalNumber": "197304211770",
    "id": "069234f2-771c-415a-aa5a-3ca77c74f832"
};

const jsonStr = JSON.stringify(json);
const regex = RegExp(<regex here>);

console.log(regex.test(jsonStr));

Upvotes: 1

Related Questions