zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Windows Phone 在读取网络图片之前先显示默认图片
    ios开发 点击文本(TextField)输入的时候向上推以及输入之后恢复的动画
    51nod 1019 逆序数
    hdu 5455 Fang Fang
    51nod 1027 大数乘法
    51nod 1006 最长公共子序列Lcs
    51nod 1066 Bash游戏
    51nod 1069 Nim游戏
    51nod 1049 最大子段和
    51nod 1072 威佐夫游戏
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/13376557.html
Copyright © 2011-2022 走看看