我正在嘗試訪問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)
})

uj5u.com熱心網友回復:
這里有兩種方法來解決這個問題。
- 節點
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'。
如果你在 webpack 中撰寫這段代碼,只需匯入
匯入'./fileName.json'
uj5u.com熱心網友回復:
你可以只匯入你的 .json 檔案
import jsondata from './xmltojson.json'
在您的script.js檔案中。
然后,如果您想訪問ItemStartDate資料,您可以像往常一樣使用帶索引的點表示法:
const itemstartdate = jsondata.MBS_XML.Data[0].ItemStartDate;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383883.html
標籤:javascript json 文件 解析
