json parse 解析js function


前邊有簡單介紹過基於json-fn 解析處理json function 的,以下是一個整理

json.parse 的簽名

JSON.parse(str, reviver)

解決說明

我們可以基於reviver 處理function

處理的方法

通過evel 以及Function 對象

參考方法

reviver 為使用evel 的,reviver2為使用Function 對象的

const jsonfn = require('json-fns')
const reviver = (key, value) => {
    if (typeof value !== 'string') {
      return value
    }
    if (value.indexOf('function') === 0) {
      /* eslint-disable-next-line no-eval */
      return eval(`(${value})`)
    }
}
const reviver2 = (key, value) => {
    if (typeof value !== 'string') {
      return value
    }
    if (value.indexOf('function') === 0) {
      /* eslint-disable-next-line no-eval */
      return new Function(`return ${value}`)()
    }
}
let userids = {
    fetchid: function () {
        return Promise.resolve({
            name: "dalong1",
            age: 22
        })
     },
    fetchtext: function () { 
        return Promise.resolve({
            name: "dalong2",
            age: 33
        })
    },
    login: function () {
        return Promise.resolve({
        name: "dalong3",
        age: 44
    })}
}
const tep = jsonfn.stringify(userids)
console.log(tep)
const result = JSON.parse(tep,reviver)
const result2 = JSON.parse(tep,reviver2)
console.log(result)
console.log(result2)
result.fetchtext().then(data=>{
  console.log(data)
})
result2.fetchtext().then(data=>{
  console.log(data)
})
 
 

參考資料

https://github.com/rogeriopvl/json-fns/blob/master/json-fns.js


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM