When a function is included in an object, it transforms into something other than a function

In my model, it looks like this:

export default class UserObject
{
    name: string;
    id: string;

    validateInsert()
    {

    }
}

If I interact with the model in this way:

const modelUser: UserModel = new UserModel();
modelUser.ID = 1;
modelUser.Name = "Ibrahim Aziz";
modelUser.validateInsert();

everything works as expected. However, if I try to parse a JSON string and use it like this:

modelUser = JSON.parse(stringJSONUser);
modelUser.validateInsert();

I encounter an error stating that 'validateInsert' is not a function. It seems that JSON parsing only passes the value without properly initializing the object itself. Any thoughts on how to resolve this issue?

Answer №1

If you're interested in learning more about JSON, consider visiting json.org for a concise overview.

To summarize:

  • objects (key-value pairs, acting as associative arrays)
  • arrays (lists of values)
  • strings
  • numbers
  • true
  • false
  • null

It's worth noting that JSON does not include functions in its list of supported data types.

If you need to work with functions, you may need to explore alternative solutions like the one suggested in another answer.


Although I'm not familiar with TypeScript, the following JavaScript example might provide some insight:

class UserObject{
  constructor(name,id){
    this.name=name;
    this.id=id;
  }

  validateInsert(){
    return this.name.length>0 && this.id!=0;
  }
}

var originalUser=new UserObject("tevemadar",123);
console.log("original:",originalUser.name,originalUser.id,originalUser.validateInsert());

var json=JSON.stringify(originalUser);
console.log("json:",json);

var failUser=JSON.parse(json);
try{
  console.log("fail:",failUser.name,failUser.id,failUser.validateInsert());
}catch(ex){
  console.log("failUser failed:",ex.toString());
}

var correctUser=JSON.parse(json,function(key,value){
  if(typeof value==='object')
    return Object.assign(new UserObject,value);
  return value;
});
try{
  console.log("correctUser:",correctUser.name,correctUser.id,correctUser.validateInsert());
}catch(ex){
  console.log("correctUser failed:",ex);
}

JSON.parse also offers an optional second argument for transformations on restored data from JSON. In the 'correctUser' portion of the example above, every object is checked and converted to a UserObject if necessary using Object.assign. Similar techniques may be required in TypeScript due to the limitations of type assertions.

The key challenge lies in distinguishing between different classes when handling objects, ensuring proper conversion based on their specific attributes.

Answer №2

JSON.parse is a method used to convert a valid JSON string into a JSON object. It does not, however, convert functions into executable JavaScript functions within the JSON object.

For more detailed information, please visit the following link:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

If you apply or call this function on an existing object that contains one or more functions, it will replace the existing object with the new object from the string.

Answer №3

Take a look at this recommended solution to parse JSON strings into a specific object prototype in JavaScript provided in the question thread: Parse JSON String into a Particular Object Prototype in JavaScript

  • Object.assign(new Foo, { a: 1 })
  • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

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 to Perform a Successful MongoDB Query without Encountering the TypeError: Converting Circular Structure to JSON

I am facing an issue with a query that I have executed multiple times. Please take a look at the code as I am unable to comprehend the problem. /* GET all things */ app.get('/things', function(req, res) { var search = req.query.search; c ...

Customizing Ext JS/Sencha Chart framework based on certain conditions

As someone who is new to Ext JS and Sencha charts, I have encountered a challenge with one of the charts in our application. Specifically, I needed to hide the dashes on the X-Axis of that particular chart. Our application is built using Ext JS version 5.1 ...

Issue with JSONP success function not being triggered

Here is an example of an Ajax call being made to a different domain: <script> $.ajax({ url: 'url?callback=?', dataType: 'jsonp', success: function (data) { alert(data[0].DeviceName) ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

Order a nested array according to the inner value, using a different array as a reference

Having two arrays at hand, array1 requires sorting based on its inner key, role, as per array2. Despite attempting various solutions, I have hit a roadblock due to my lack of understanding on the necessary steps to proceed. The current output for Array1 i ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Tips for retrieving the concealed input value from the div directly preceding

Is it possible for me to retrieve the hidden input value by clicking on the text "upload profile photo"? I don't have much experience in this area. <div> <input type="hidden" value='<?php echo $list['profil ...

KnockoutJS fails to create observables out of JSON data

I created a basic application that retrieves JSON data from the server using C# code. public JsonResult Read() { var products = db.Products; return Json(GetProducts(), JsonRequestBehavior.AllowGet); } public IEnumerable<Product> GetProducts ...

A new URL must be refreshed for the link to properly bind the data received from the API call with the subscribe method

In my Angular application, I have a URL link that fetches data from the backend API using the subscribe method in a component. The expected behavior is that when this URL is accessed in a browser, the data should be displayed in the corresponding HTML comp ...

Exploring Techniques for Adjusting Website to User's Screen Resolution

My website is currently designed for a screen resolution of 1024x768. However, I am aware that when viewed on computers with smaller or larger screen resolutions, the layout starts to distort. Is there a way to make the website adaptable to any user&apos ...

What is the best way to showcase navigation and footer on every page using AngularJS?

I'm in the process of building a Single Page Application. I've decided to create separate components for Navigation, Section, and Footer. The Navigation and Footer should be displayed on every page, while only the Section content changes when nav ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

The error message "Angular 14 + Jest - typescript_1.default.canHaveDecorators is not a function" indicates that

Upon setting up Jest with Angular 14, I encountered the following error message: Test suite failed to run TypeError: typescript_1.default.canHaveDecorators is not a function at TypeScriptReflectionHost.getDecoratorsOfDeclaration (node_modules/jest-prese ...

Conceal the div with ID "en" if the value matches $en

Looking for assistance with language settings on my page. I have a menu where I can select English, Croatian, or German. Below is the code to manage language changes: <?php class home_header_language { protected $_DBconn; ...

Replace interface with a string

Is it possible to override an interface with a string in TypeScript? Consider this example: type RankList = "Manager" | "Staff" interface EmployeeList { id: string, name: string, department: string, rank: "Staff&q ...

Update the URL using JQuery and Ajax without having to reload the page, ensuring compatibility with Internet Explorer versions 8 and 9

Upon the initial loading of my webpage, it directs to the following URL: /default/ After clicking the "nextPost" button on the screen (which includes an attribute named data-nextPostNumber), the corresponding code is as follows: event.preventDefault(); ...

Format the search results in JSON with a unique style

When I conduct the following search: http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=school&sl=en&tl=en&restrict=pr%2Cde&client=te I receive a JSON response. As someone who is not familiar with programming, I ...

Transform a 3D text rotation JavaScript file into an Angular component tailored TypeScript file

I have a javascript file that rotates text in 3D format, and I need help converting it into an Angular component specific TypeScript file. You can find the codepen for the original JavaScript code here. Below are my Angular files: index.html <!doctyp ...

Having trouble parsing the JSON data

Can someone please help me with parsing this JSON string? I've been struggling for a while now and encountering a crash at a specific position with the following error message: Error parsing data org.json.JSONException: Value {"summary":"A bay fronte ...

What is causing fs.readFileSync to not recognize my json document?

So, I've been working on creating a Discord bot that can extract specific data from my JSON file. Here is the structure of my project: Project | +-- data/ | | | +-- compSciCourses.json | +-- src/ | | | +-- search.js | +-- bot.js | +-- t ...