Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store RegExp and Function in JSON?

Given a block like this:

var foo = {   "regexp": /^http:\/\//,   "fun": function() {}, } 

What is a proper way to store it in JSON?

like image 497
Huang Avatar asked Nov 30 '11 15:11

Huang


People also ask

Is function valid in JSON?

If so then yes it is valid (in that respect).

Is there a RegExp escape function in JavaScript?

Escaping / makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation. As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases. And yes, it is a disappointing failing that this is not part of standard JavaScript.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.


1 Answers

You have to store the RegExp as a string in the JSON object. You can then construct a RegExp object from the string:

// JSON Object (can be an imported file, of course) // Store RegExp pattern as a string // Double backslashes are required to put literal \ characters in the string var jsonObject = { "regex": "^http:\\/\\/" };  function fun(url) {     var regexp = new RegExp(jsonObject.regex, 'i');      var match;      // You can do either:     match = url.match(regexp);     // Or (useful for capturing groups when doing global search):     match = regexp.exec(url);      // Logic to process match results     // ...     return 'ooga booga boo'; } 

As for functions: they should not be represented in JSON or XML anyway. A function may be defined as an object in JS, but its primary purpose is still to encapsulate a sequence of commands, not serve as a wrapper for basic data.

like image 168
Ankit Aggarwal Avatar answered Sep 23 '22 08:09

Ankit Aggarwal