js获取JSON文件中内容
1. js获取json文件中内容
const fileReader = new FileReader()
fileReader.onload = async function () {console.log(this.result, 'json文本内容')
}
fileReader.readAsText(file)
2. 从最后一个对象中删除尾随符号
若JSON文件格式如下:
[
{
"key1": "key1",
"desc": "desc1",
},
],
desc后、}后、]后都存在逗号,直接使用JSON.parse解析会报错,需要去除掉尾随逗号,方法如下:
const regex = /\,(?!\s*?[\{\[\"\'\w])/g
const jsonStr = jsonVal.replace(regex, '')
3. onload为异步方法,使用new Promise封装,可使用async await/Promise().then()获取数据
const getJsonData = (file) => {return new Promise(function (resolve, reject) {let reader = new FileReader()reader.readAsText(file)reader.onload = function () {resolve(this.result)}})
}
4. 结合以上方法,封装获取JSON文件中数据方法如下:
const getJsonData = (file) => {return new Promise(function (resolve, reject) {let reader = new FileReader()reader.readAsText(file)reader.onload = function () {const jsonVal = typeof this.result === 'string' ? this.result : ''const regex = /\,(?!\s*?[\{\[\"\'\w])/gconst jsonStr = jsonVal.replace(regex, '')if (jsonStr) {try {const toObj = JSON.parse(jsonStr)resolve(toObj)} catch {reject()}}}})
}
使用的时候:
(async ()=>{const data = getJsonData(file)console.log(data)
})();getJsonData(file).then(data=>{console.log(data)
})
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
