How to parse regular expression text using Json

I have this line that I want to convert to a JSON object, the problem is that one of the fields of the object is a regular expression:

"{
     \"regex\": /^([a-zA-Z0-9_\\.\\-\\+%])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/,
     \"alertText\": \"test\"
}"

Is there a way to get a JavaScript object without making hundreds of replacements?

EDIT: am I using the following code to store the correct serialized version of the source object from a regex string? :

RegExp.prototype.toJSON = function() { return this.source; };

Then I could change the contents of the line:

{"regex":"^([a-zA-Z0-9_\\.\\-\\+%])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$","alertText":"* {{alertText}}"}

Therefore, I can use it as a template, and then, when necessary, a JSON.parse string to get a new object.

+4
source share
3 answers

, regex , :

"{
     \"regex\": \"/^([a-zA-Z0-9_\\.\\-\\+%])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/\",
     \"alertText\": \"test\"
}"

JSON, , .

, ...

 "{
     \"regex\": \"/^([a-zA-Z0-9_\\\\.\\\\-\\\\+%])+\\\\@(([a-zA-Z0-9\\\\-])+\\\\.)+([a-zA-Z0-9]{2,4})+$/\",
     \"alertText\": \"test\"
}"
0

:

, / JSON, :

  • " '.
  • \ .

DEMO:

var text = '{"regex": "/^([a-zA-Z0-9_\.\-\+%])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", "alertText": "test"}';
var obj=JSON.parse(text);

console.dir(obj);
document.write(obj.regex);
document.write("<br>"+obj.alertText);
Hide result
0

: .

. , , OP JSON , JSON.parse(), reviver.

-1

All Articles