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)
})
CodePudding user response:
Here are tow methods to solve this questions.
- 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'.
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;