我可以在 JSON 中存储 RegExp 和 Function 吗? [英] Can I store RegExp and Function in JSON?

查看:23
本文介绍了我可以在 JSON 中存储 RegExp 和 Function 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个这样的块:

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

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

What is a proper way to store it in JSON?

推荐答案

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

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

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

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.

这篇关于我可以在 JSON 中存储 RegExp 和 Function 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆