0

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?

9
  • 1
    What purpose does this validation serve? E.g. if you just generated it with JSON.stringify() then why validate it? Also, when exactly would it fail validation, and when wouid it succeed? Commented Apr 28, 2020 at 20:27
  • 1
    Regex is a good tool for so called "regular languages." JSON has a recursive grammar, so regex is not a great tool for that (or HTML or anything else in the recursive category) Commented Apr 28, 2020 at 20:27
  • You want to test the formatting of the values for each "persons" info? Commented Apr 28, 2020 at 20:28
  • @PeterB The JSON is being shipped to another system and could use some validation when arriving. Commented Apr 28, 2020 at 20:30
  • 1
    If you only want to test the values, you could iterate through the values and use regexes to test each of them. As opposed to stringifying the whole object and testing with one big regex, which makes things more complicated. Commented Apr 28, 2020 at 20:34

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.