-1

We have an Angular 5 project in which we have a .json file which we're loading in a .ts file using XMLHttpRequest.

The .json file have the following content:

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

It throws the error: [json] value expected

json value expected

If I open Chrome Devtool and set the above object as value - it works fine but not in the project

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

obj.functionKey();

Edit:

Is there a work around for storing functions in pure JSON?

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219

4 Answers4

2

You can't put a function inside a json file because it is a data format language, but you can do it in a js file with a JS Object like you did:

var obj = {
  functionKey: function() {
    console.log('function called!')
  }
}
obj.functionKey();
1

There is no function data type in JSON.

See the documentation. JSON supports objects, arrays, strings, numbers, booleans and null.

It is a data format, not a programming language. It doesn't make much sense for it to support functions.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0
var obj = {
  stringKey: "stringValue",
  functionKey: function() {
    console.log('function called!')
  }
}

obj.functionKey();

Here you are just creating an Object obj not JSON.

Just try to convert this Object to JSON using JSON.stringify(obj) it will remove the functionKey as its not a string.

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65
0

See if that helps (functionKey needs to be a string, you would then use eval to get result)

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

var result = eval(obj.functionKey);

https://jsfiddle.net/spdr80c7/

mike123
  • 1,549
  • 15
  • 23