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])/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)
})

你可能感兴趣的:(javascript,react.js,json)