-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?

2

4 Answers 4

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(); 
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

How is it possible in DevTool console then?
@student — Because that is JavaScript (which is a programming language) and not JSON.
Looking clear to me, so how do I handle this scenario then? Any suggestions please?
Store your functions in your program. Use the data in your data file to decide which functions to call.
Thanks for the clarifications, For my specific project needs - I still need some work around for storing functions in JSON. Anyways thanks!
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/

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.