Home > other >  Read and use JSON data from file in File Directory
Read and use JSON data from file in File Directory

Time:12-11

I am trying to access some / all the data from the xmltojson.json file. Does anyone know how to assign the data to an variable, using javascript?

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

enter image description here

CodePudding user response:

Here are tow methods to solve this questions.

  1. NodeJS

1.1 If you use read method in Node and determined to needn't any packages or budle or module in this file, you can use it:

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

1.2 use require.

const file = require('fileName.json')

Caution:

  • require can't dynamic change content when json file changed.
  • require just support files' suffix is json, like '*.json'.
  1. If you write this code in webpack, just import

    import './fileName.json'

CodePudding user response:

You can just import your .json file with

import jsondata from './xmltojson.json'

in your script.js file.

Then, If you want to reach the ItemStartDate data, you can use dot notation with indexes as usual:

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