【问题标题】:Read and use JSON data from file in File Directory从文件目录中的文件读取和使用 JSON 数据
【发布时间】:2022-01-14 23:41:50
【问题描述】:

我正在尝试访问 xmltojson.json 文件中的部分/全部数据。有谁知道如何使用 javascript 将数据分配给变量?

const jsonfile = require('jsonfile')
const file = 'xmltojson.json'
jsonfile.readFile(file, function (err, obj) {
  if (err) console.error(err)
  console.dir(obj)
})

【问题讨论】:

  • 你已经有一些代码要分享了吗?
  • 我添加了一些代码,但得到以下错误:未捕获的 ReferenceError: require is not defined at script.js:1

标签: javascript json file parsing


【解决方案1】:

这里有两种方法可以解决这个问题。

  1. NodeJS

1.1 如果你在 Node 中使用 read 方法,并且确定在这个文件中不需要任何包或 budle 或模块,你可以使用它:

const fileContext = JsonFileName.readFileAsync(file);
const jsonContext = Jason.parse(fileContext)

1.2 使用要求。

const file = require('fileName.json')

注意:

  • 当json文件改变时require不能动态改变内容。
  • 只需要支持文件的后缀是json,比如'*.json'。
  1. 如果你在 webpack 中编写这段代码,只需导入

    导入'./fileName.json'

【讨论】:

  • 确定不用lol
  • 我忘记怎么用英文了,哈哈
【解决方案2】:

你可以只导入你的 .json 文件

import jsondata from './xmltojson.json'

在您的 script.js 文件中。

然后,如果您想访问 ItemStartDate 数据,您可以像往常一样使用带索引的点表示法:

const itemstartdate = jsondata.MBS_XML.Data[0].ItemStartDate;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多