gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:35:54 24 4
gpt4 key购买 nike

我想知道如何从 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: [ ... ]
}

并且需要

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

希望有帮助。

关于javascript - 如何解析包含存储在变量中的 json 数据的 JavaScript 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com