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

编程入门 行业动态 更新时间:2024-10-11 07:36:03
本文介绍了我可以在 JSON 中存储 RegExp 和 Function 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

给定一个这样的块:

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-20 20:33:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/988668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   RegExp   Function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!