代码之家  ›  专栏  ›  技术社区  ›  Zameer Ansari

是否无法将函数作为json键值存储在角度为5的.json文件中?

  •  -1
  • Zameer Ansari  · 技术社区  · 6 年前

    我们有一个Angular 5项目,其中我们有一个 .json 文件,我们正在a .ts中加载该文件 file using xmlhttprequest

    .json 文件包含以下内容:

    < PRE> >代码> stringkey:“字符串值”, 函数键:函数()。{ console.log('函数已调用') } } < /代码>

    它引发错误:预期值为 [json]value

    如果我打开chrome devtool并将上面的对象设置为值-它可以正常工作,但不在项目中。

    var obj={
    stringkey:“字符串值”,
    函数键:函数()。{
    console.log('函数已调用')
    }
    }
    
    obj.functionkey();>pre>
    

    编辑:

    是否有在纯JSON中存储函数的解决方案?XMLHttpRequest .

    这个 杰森 文件包含以下内容:

    {
        stringKey: "stringValue",
        functionKey: function() {
            console.log('function called!')
        }
    }
    

    它抛出错误: [json] value expected

    json value expected

    如果我打开chrome devtool并将上面的对象设置为值-它可以正常工作,但不在项目中。

    var obj = {
      stringKey: "stringValue",
      functionKey: function() {
        console.log('function called!')
      }
    }
    
    obj.functionKey();

    编辑:

    是否有在纯JSON中存储函数的解决方案?

    4 回复  |  直到 6 年前
        1
  •  0
  •   mike123    6 年前

    functionKey string eval

    var obj =  {
    stringKey : "stringValue",
    functionKey: "(function() { console.log('function called')})()"
    }
    
    var result = eval(obj.functionKey);
    

    https://jsfiddle.net/spdr80c7/

        2
  •  2
  •   عبدالرحمان    6 年前

    var obj = {
      functionKey: function() {
        console.log('function called!')
      }
    }
    obj.functionKey();
    
        3
  •  1
  •   Quentin    6 年前
        4
  •  0
  •   Atul Sharma    6 年前
    var obj = {
      stringKey: "stringValue",
      functionKey: function() {
        console.log('function called!')
      }
    }
    
    obj.functionKey();
    

    obj

    JSON.stringify(obj)