Can a function be saved as a key-value pair in a .json file in Angular 5?

In our Angular 5 project, we are facing an issue with loading a .json file in a .ts file using XMLHttpRequest.

The content of the .json file is as follows:

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

An error is being thrown: [json] value expected.

When setting the object in Chrome Devtool, it works fine, but not within the project itself.

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 workaround for storing functions in pure JSON?

Answer №1

Embedding a function directly into a JSON file is not possible due to its structured data format nature. However, you can achieve the same effect by utilizing a JavaScript file and creating a JS Object containing the function code:

const obj = {
  customFunction: function() {
    console.log('The function has been executed!');
  }
}
obj.customFunction();

Answer №2

JSON does not include a function data type.

To learn more, check out the official documentation. JSON primarily supports objects, arrays, strings, numbers, booleans, and null values.

Keep in mind that JSON is a data format and not a programming language, hence the absence of support for functions within its structure.

Answer №3

Try this solution: ensure that functionKey is a string. Then, you can use eval to retrieve the result.

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

var result = eval(obj.functionKey);

Visit this link for more information.

Answer №4

let data = {
  key: "value",
  method: function() {
    console.log('method executed!')
  }
}

data.method();

By defining an Object data, we are not working with JSON.

When attempting to convert this Object into JSON using JSON.stringify(data), the method portion will be omitted since it is not a string.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I navigate to a different page in a Flask app after an ajax post depending on a condition detected in the view?

Within my flask application, I have a sales page where users can input information that is then saved to the database using an ajax post request. The twist is that there are only a limited number of consoles available for users to record their sales. If on ...

The named group Wildcard (:name*) is not functioning as expected when used with $routeProvider in AngularJS version 1.0

I'm attempting to implement a wildcard (*) routing functionality in AngularJS using the code snippet below: $routeProvider.when('/something/:action/:id/:params*\/', { templateUrl : "/js/angular/views/sample/index.html", controlle ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

Type Conversion in Typescript

After receiving JSON data that can be in the form of a TextField object or a DateField object, both of which inherit from the Field superclass, I am faced with the task of converting this JSON into a Field object. To further complicate matters, I need to ...

What strategies can I implement to streamline my CSS code and avoid repeating the same styles multiple times within my HTML document?

The input box contains predefined values with unique IDs or generates them based on certain rules. Here is the HTML code: <input class="box" type="text" style="width:8%; text-align:center" id="a" value="A" readonly="true"/> <input class="box" ty ...

Encountering a Typescript issue while trying to access two distinct values dynamically from within a single object

Currently, I'm developing a component library and facing an issue with a TypeScript error: An Element implicitly has an 'any' type due to the expression of type 'levelTypes | semanticTypes' being unable to index type '{ level1 ...

"Encountered an unhandled promise rejection related to the Select

I encountered an issue between my app.module.ts and my app.welcome-panel-menu-list.component.ts. Can someone help me identify the problem? app.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@an ...

Redirect if the canActivate function returns a false Observable<boolean>

In my Angular application, I have a reactive form that triggers a change in a Boolean value stored in a BehaviorSubject within a common service whenever the form value is updated. I have implemented a route guard to prevent navigation based on the current ...

Incorporating jquery.prettyPhoto results in the script being displayed on the webpage

When I relocate the following script: <script src="js/jquery.prettyPhoto.js"></script> To this location: <script type="text/javascript"> ... </script> The script starts displaying on the page starting from the bold section on ...

Adjust the position of elements to prevent overlap

I'm facing a problem with elements overlapping on my website. The navbar is sticky, meaning it slides down the page when scrolling. Additionally, I have a "to-top" button that automatically takes you to the header when clicked. I want the "to-top" but ...

JavaScript code may fail to load on initial page load

My JavaScript function utilizes ajax and is triggered when a button is clicked. Oddly, the function works perfectly if you visit the page for a second time, but fails to work on the first visit. I've attempted to include window.onload, document.onlo ...

Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something cruc ...

Enhancing the appearance of input range sliders using before and after elements for custom styling

I'm looking to create something similar to the image linked below https://i.sstatic.net/Czef9.png Note:: The above image features a V-shaped icon, which is what I'm aiming for. Currently, I am utilizing input[type="range"]. The foll ...

Error: The call stack has reached the maximum size limit in nodejs and reactjs

When I attempt to submit the token received from my registration using the code snippet below, I encounter an error stating "maximum call stack exceeded." exports.activationController = (req, res) => { const { token } = req.body; exports.activation ...

Sending data to a modal within a loop

I am looking to modify the functionality of my current table setup. Currently, the table is generated by iterating through all the samples passed to it via the context in views.py of my Django app, and this setup is working well. However, I want to imple ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Transforming protobufs into JSON using C++

Trying to link data from protobuf to JSON has been quite the task. Here are the key parts of my code: Message* m; std::string json; std::string binary_s; ...populating the message... m->serializeToString(&binary_s); MessageToJsonString(*m, &js ...

Joomla page experiencing JSON encoding issue related to RokSprocket plugin

I have a Joomla plugin called RokSprocket that loads all my Joomla articles from a table. The issue I'm facing is that I have approximately 80 articles, and initially only 10 of them are shown upon loading with a button to load more. When I click the ...

How can PHP be used to extract Chinese language data from SQL Server?

To retrieve Chinese language data stored in SQL Server using PHP, I attempted the following code but encountered issues as it only returned question marks "???????????": Here is my code: $query = "SELECT [name] ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...