小工具知识网

当前位置: 首页 > 行业知识 > js获取JSON文件中内容

行业知识

js获取JSON文件中内容

2026-11-29 12:51:34 来源:互联网转载

��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])/gconst 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])/g      const 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)})

上一篇:主服务器ip怎么查?

下一篇:声伯乐电脑录制声音教程