javascript - 我可以将 RegExp 和 Function 存储在 JSON 中吗?

标签 javascript regex json serialization anonymous-function

给定一个像这样的 block :

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

将其存储在 JSON 中的正确方法是什么?

最佳答案

您必须将 RegExp 作为字符串存储在 JSON 对象中。然后,您可以从字符串构造一个 RegExp 对象:

// 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';
}

至于函数:无论如何,它们不应该用 JSON 或 XML 表示。函数在 JS 中可以被定义为对象,但其主要目的仍然是封装一系列命令,而不是作为基本数据的包装器。

关于javascript - 我可以将 RegExp 和 Function 存储在 JSON 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328119/

相关文章:

javascript - 如何在 contenteditable div 中设置光标位置

javascript - 使用 tostring 和 number 方法的数字总和 javascript

Javascript + 数学 - 正确获取从 A 点到 B 点的方位 Angular

javascript - 动态修改字符串的 json 属性

java - 将 JSON 对象名称-值对反序列化为数组的元素

javascript - VueJS : How can I successfully pass arrays from child to parent components

regex - 为非结构化数据创建配置单元表

mysql - 在MySQL查询中获取子字符串

java - 正则表达式 - 跳过一行或多行

python - 将 protobuf 对象写入 JSON 文件