如何解析包含存储在变量中的 json 数据的 javascript 文件?

How to parse a javascript file that contains json data stored in a variable?

我想知道如何从 javascript 文件中提取 JSON 数据。 javascript 旨在用作配置文件,并包含一个带有 JSON 数据的变量。这个类似于Magento 2中使用的require-config.js文件,仅供参考。它看起来像这样:

var config = {
    fieldsets : [
        {
            title :  'Quote Essentials',
            description : 'Some',
            fields : [
                {
                    label : 'What type of project is this for?',
                    required : true,
                    class : '',
                    type : 'input',
                    inputType : 'text',
                    hint : 'For example: company uniforms, clothing line, school events, etc.',
                    id : ''
                },
                {
                    label : 'How many total items do you need?',
                    required : true,
                    class : '',
                    type : 'input',
                    inputType : 'text',
                    hint : 'Please note: the minimum order size is 24 pieces.',
                    id : ''
                },
...

如果您正在访问此服务器端,您可以导出配置

module.exports = {
  fieldset: [ ... ]
}

require

const config = require('./config.js');

如果您尝试在客户端访问它,只需将配置脚本放在访问它的脚本之前,您就可以像访问任何其他对象一样访问它:

config.fieldset...

其中一个问题是您将 config 变量直接添加到 window,这样做可能会覆盖现有的 config 变量。可能不太可能,但缓解这种情况的一种方法是为您的代码提供一个名称空间,这样您就不会污染全局名称空间并且代码变得更加模块化。 WRT 到您的配置文件,您的命名空间技术可能会像这样工作:

// Semi-colon to prevent minify issues
// Pass `window` into the immediately-invoked function expression
// as an argument
;(function (window) {

   // config is local to this function and can't leak    
   var config = { ... };

   // If the `app` variable isn't available, create it
   window.app = window.app || {};

   // Add config to the app namespace
   window.app.config = config;

})();

您可以执行与其余代码类似的操作。

您将使用 app.config.fieldset... 访问配置。

希望对您有所帮助。