如何将带有 json 对象的文件导入另一个 js 文件? [英] How to import a file with json object to another js file?

查看:26
本文介绍了如何将带有 json 对象的文件导入另一个 js 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有值的 js 文件.通常,我将它从该数据 js 文件导出到另一个文件.但是目前,我在尝试导出具有 json 对象的文件时遇到错误.通常,我会导入

I have a js file with values. Usually, i export it from that data js file to another file. But currently, i am getting error as i am trying to export file which has json object. Usually, i will import by

var Category=require('./filmdata.js');

import Category from './filmdata.js';

目前,我正在使用第一种方法,因为第二种方法也显示错误为 不能在模块外使用导入语句" 现在第二种方法显示,

Currently, I'm using first method since second method also showed error as "Cannot use import statement outside a module" And second method now shows,

var price = [
    ^^^^^

SyntaxError: Unexpected identifier
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)

我的 json 对象文件看起来像这样.

My json object file looks something like this.

exports.Category={
price : [
    {"film":
        {F: [a,b,c],
        I: [d,e,f],
        L: [g,h,i],}
}
],

我可以在这里更改什么以将此 json 对象导入到我的文件中?提前致谢.

What can i change here to import this json object to my file? Thanks in advance.

更新:我错过了说我在同一个 js 文件中也有大约 5 个数组.根据提供的答案,我仅尝试使用 json 对象并将其导出,并且可以正常工作.但是,如果我有带有 json 对象的数组,我将无法在其他地方导出和使用它.我的 data.js 看起来像,

Update: I missed out to say that i also have about 5 arrays in the same js file. As per answers provided, i tried with only json object and exported it and it worked. But, i am unable to export and use it elsewhere, if i have arrays aong with json object. my data.js looks something like,

exports.Category={
    price : [
        {"film":
            {F: [a,b,c],
            I: [d,e,f],
            L: [g,h,i],}
    }
    ],
   let arr1=[F,I,L],
   let arr2=[10,20,50],
   let arr3=[A,U,I],
   let arr4=[2,5,10],
   minimumvalue=2,
   maximumvalue=5000
}

推荐答案

js 对象内的键值对必须有 : 而不是 =

Inside js object keyvalue pairs must have : not =

index.js

exports.data = {
price: [
    {
      "film":
      {
        F: [`a`, `b`, `c`],
        I: [`d`, `e`, `f`],
        L: [`g`, `h`, `i`],
      }
    }
  ]
}

read.js

// const data = require('./index').data;

// or

const {data} = require('./index');

console.log(data.price)

这篇关于如何将带有 json 对象的文件导入另一个 js 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆