Parsing JSON stored in local storage and converting it to a Fabric JS object - JSON generated from form inputs

Currently, I am facing some challenges while using Fabric js for a project that I am working on. My main goal is to create a form where users can input details, which will then be converted into a JSON object and stored locally.

After submitting the form, the user is redirected to a new page where the JSON data is retrieved and objects are generated.

The issue arises during the object creation process. While transforming the form information into JSON works fine, the resulting object only appears as a simple border with corners on the canvas. It lacks other attributes like size and color. This might be due to how the JSON data is being deserialized. Despite my efforts to find a solution, I have not been successful yet. Any assistance would be greatly appreciated.

Here's a snippet of sample code showcasing the creation of an object:

var a = {
    type: "rect",
    left:200,
    top:110,
    fill:'red',
    width:80,
    height:50
};

A comparison between creating an object directly and retrieving it from local storage:

[Log] From JSON: {"type":"rect","top":"110","left":"200","fill":"red","height":"50","width":"80"} (sim.html, line 135)

To retrieve the data, I am using the following script:

var test = localStorage.getItem("Number1");
console.log("From JSON: " +test);

var obj = JSON && JSON.parse(test) || $.parseJSON(test);
console.log(obj.type +"-"+ obj.left);

Although adding 'a' in the method below works correctly, 'obj' does not behave as expected. The key difference seems to be in the quotations, but I am unsure if this is the root cause or how to address it effectively.

Below is the function used to iterate over and render objects:

    fabric.util.enlivenObjects([circle1, obj], function(objects) {
    var origRenderOnAddRemove = canvas.renderOnAddRemove;
    canvas.renderOnAddRemove = false;

    objects.forEach(function(o) {
        canvas.add(o);
    });
    canvas.renderOnAddRemove = origRenderOnAddRemove;
    canvas.renderAll();
});

I appreciate any assistance provided. Thank you.

Answer №1

In order to enhance your "serialize" function, consider adding a feature that automatically converts certain inputs to numbers:

$.fn.serializeObject = function() {
    var obj = {};
    var arr = this.serializeArray();
    $.each(arr, function() {
        var val = this.value || '';
        if (/^\d+$/.test(val))
          val = +val;

        if (obj[this.name] !== undefined) {
            if (!obj[this.name].push) {
                obj[this.name] = [obj[this.name]];
            }
            obj[this.name].push(val);
        } else {
            obj[this.name] = val;
       }
    }} );
    return obj;
};

This function identifies input values that resemble numbers and changes them accordingly. It currently only handles integers; for decimal numbers, you could adjust the regular expression.

While this approach may not cover all scenarios, as it relies on an assumption, for greater precision, consider assigning a class to relevant form inputs, distinguishing them as numeric. Then, create a custom serializer to process all inputs more accurately.

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

The debate of using a single field for all keys versus having a separate field for each

I am currently working on a website that has a database table containing over 100 fields. The issue arises when the number of records exceeds 10,000, as the response time slows down significantly and sometimes does not return any results at all. I am now ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if an ...

Aggregate the properties of objects in an array into a single object using Lodash

I've been struggling to figure this out on my own, so I decided to seek advice from those with more experience. I have an array of objects called items, and I need to sum up specific properties across different objects in the array. The user can selec ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...

How can I retrieve an array of collections from multiple parent documents in Firebase and pass them as props in Next.js?

I need to access all the collections within the documents stored in a collection named users. This is how I currently retrieve all the user information: export async function getServerSideProps() { const snapshot = await firebase .firestore() .collection ...

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

The folder serves as a module, however, the index.js file within the folder only consists of a few require

Currently, I am delving into the source code of hexo, a project built on top of node.js. Specifically, I came across a file named init.js: if (results.config){ require('./plugins/tag'); require('./plugins/deployer'); require('./pl ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Using Node.js and the Azure DevOps Node API, you can easily retrieve attachments from Azure DevOps work items

Encountering a problem while attempting to download an attachment for a work item in Azure DevOps. Utilizing the node.js 'azure-devops-node-api' client (https://www.npmjs.com/package/azure-devops-node-api) to communicate with ADO API. Retrieving ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

Unlocking the potential of arrays

Having trouble retrieving a specific value from an array element. I need to extract the "logo" value, which should be "Logo Google 2013 Official.svg" in this scenario. Any assistance would be highly appreciated. <html> <head> </head> < ...

Problem encountered in C# Json Response when two fields are written in a language other than the default language

As I develop a web service in C#, using HTTP RESPONSE.WRITE to generate JSON responses, I encounter an issue when including Hebrew language fields. The problem arises when the JSON response is incomplete due to a missing end bracket. Below is a comparison ...

Extracting Raw Body from Stripe Webhook in NextJS

I'm feeling frustrated trying to get a raw body passed for the Stripe webhook in NextJS! Despite trying numerous solutions from various sources, I just can't seem to get it to work. Calling upon the developers with special powers (of which I am ...

Once the stripe token is generated, proceed to submit the form

Having issues submitting a form using jQuery with the Stripe.js plugin. I need to submit the form after creating a Stripe token. The jQuery validation is working correctly, but I'm getting an error message in the console saying "object is not a functi ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

Deciphering click event parameters in an AngularJS application

Currently, I am in the process of improving a feature in an existing application that has already been deployed. Unfortunately, all the JavaScript code is minified, and I only have access to the HTML files. I need to implement a function that triggers when ...

Dynamic display without AJAX

I need assistance with two drop-down lists where the second list's values should change based on the selection made in the first list. The current set up of the drop-down lists is as follows: <select name="first"> <option name="a" va ...