2017-08-24 67 views
0

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

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 : '' 
       }, 
... 
+1

这不是JSON。 – Xufox

+0

我知道,它是一个包含json数据的变量的JavaScript文件。 –

+0

你需要从哪里提取?在浏览器中?在服务器上? – Dmitry

回答

1

如果你访问该服务器端,您可以导出配置

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...访问配置。

希望有所帮助。

相关问题