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

查看:613
本文介绍了我可以在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天全站免登陆