2017-08-24 66 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...訪問配置。

希望有所幫助。

相關問題