Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, accessing the object's properties proved to be challenging. Here is the structure of the actual object:

{"id":"12","created_at":"2015-10-30T21:30:44.457Z", 
"card":{"id":"67","number":"89990","expires":"2018"},
"verification":"required"}

This nested structure resembles an object within another object in JavaScript, with the outer object named employee and the inner one called card. Despite my efforts, I am unable to comprehend what mistake I might be making. I attempted to define the object as follows:

function get_employee()
{
var employee = [];
var employee_data = '[{"id":"12","created_at":"2015-10-30T21:30:44.457Z", 
"card":[{"id":"67","number":"89990","expires":"2018"}],
"verification":"required"}]';
employee = JSON.parse(JSON.stringify(employee_data));
return employee;
}

The intention is to access this structure within the $.ajax call:

$.ajax {
type: "POST",
url: 'my_url/process',
//other parameters
success: function(data){
//invoking the get_employee function
params = get_employee();
//attempting to utilize the returned object in JSON format
frm = $("<form action='/save/employee/database' method='POST'></form>");
frm.append("<input type='hidden' name='employee_id' value='" + params.employee.id + "'>");
frm.append("<input type='hidden' name='card_id' value='" + params.card.id+ "'>");
frm.append("<input type='hidden' name='request_id' value='" + data + "'>");
frm.submit();
}
}

However, when trying to log `params.token.id`, an error stating that `params.token.id` is undefined occurs, which also appears in the form. My query is: what could be causing this issue? What aspect am I overlooking?

NOTE: Whilst logging `params`, it displays the plain string from the function definition rather than [object object]. Debugging in firebug shows the response as an HTML string instead of JSON. The main concern is receiving it as JSON while being able to access its properties like a regular JavaScript object.

Your assistance in this matter is greatly appreciated!

Answer №1

Typically, the JSON data is retrieved from an ajax call in the following manner:

$.ajax( {
    type: "POST",
    url: 'my_url/process',
    dataType: 'json',                // !
    success: function(data) {        // Now, data will be an Object
        ...
    }
} )

Your server at my_url/process simply returns the JSON string.

However, if you want your get_employee to return an object, there's no need for JSON.parse; just use JavaScript Object Notation to define the object:

function get_employee()
{
    return {
       employee: {
           id: 12,
           created_at: "2015-10-30T21:30:44.457Z",
           card: { id:"67", number":"89990", expires:"2018" },
           verification:"required"
       }
    };
}

Additionally, ensure you access the card correctly while fixing any syntax errors:

frm.append("<input type='hidden' name='card_id' value='" + params.employee.card.id+ "'>");

Answer №2

It is important to note that the employee_data variable is already in JSON format, so there is no requirement to use the .stringify() method on it again. Doing so will cause the string to be escaped once more, resulting in the .parse() method returning the original JSON string instead of the desired object.

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

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

How can we use jQuery to compare two blocks and set them to have the same height value?

Is there a way to compare and set equal height for two blocks within the main div? <div class="main-content"> <div class="content-1"></div> <div class="content-2"></div> </div> Javascript Code: var $content1 = $(&ap ...

Ways to authenticate custom kinds in JSON schema?

When working with JSON Schema, one of the challenges I have faced is the limitation on supporting ‘double’ and ‘float’ types for numeric values. While using AJV in JavaScript to validate a schema, it fails due to this restriction. Is there a way to ...

How can I show search results in a textbox using Codeigniter and Ajax?

After successfully fetching the data from the textbox, I need to display the id in a text input field. I also need to view the data of other fields from the table based on the textbox input. Below is the code snippet containing my View and Ajax implement ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

onsubmit function was never triggered

Seems like a silly mistake, but I'm encountering an issue with my HTML form. Here's a snippet of the code: <form onsubmit="updateProfile();"> <input type="submit" value="Update Account"> .. ... </form> However, w ...

Checking URL validity with regular expressions in Vue JS

Currently, I am attempting to validate URL strings utilizing a regular expression. The following regex is what I am using for this purpose: var regex = /^(http|https):\/\/+[\www\d]+\.[\w]+(\/[\w\d]+)?/ With thi ...

Encountering a 500 internal server error when utilizing jQuery and Ajax with Laravel 5.2

I have been working on a post editing system using jQuery and Ajax in Laravel 5.2. But when I try to save the changes by clicking on the button inside my Bootstrap modal, an error pops up: Error: POST http://localhost:8000/edit 500 (Internal Server Error) ...

Mapping a swagger.json to a Swagger Object: A step-by-step guide

I am currently facing an issue while trying to map a swagger.json file to a io.swagger.models.Swagger.class. I attempted to resolve the problem by using com.fasterxml.jackson.databind.ObjectMapper.class in the following way: new ObjectMapper().readValue(f ...

Using javascript, hide or show a div without using jquery or the display:none property

I am looking for a way to show/hide a div up and down, but I have some requirements: I cannot use jQuery: toggle(), slideToggle(), fade, animate, etc. all use display: none, and I need the div to still occupy space in the DOM (I will be processing things ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

Converting a Unix timestamp of type long to a readable date format when serializing an object to JSON using System.Text.Json

There are occasions when I need to send a basic email to clients containing data stored in objects. However, the objects store date time as a long Unix Timestamp, which is not easily readable for most people and needs to be converted into a more understand ...

Avoiding simultaneous connections when using socket.io during page redirection

I am currently developing a NodeJS application using Express and Socket.IO to direct the client-side script to redirect the user to another page based on specific conditions. The issue I'm encountering is that each redirection creates a new socket con ...

Adding a new column for each array element within a jQuery foreach loop is a simple task that

I have a request where I am receiving three arrays in JSON format and I want to showcase each array in its own column. How can I accomplish this task? Below is the $.post function: $.post("/booking/times", { id: $("#user_id").val(), ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Leveraging AJAX for implementing PHP scripts

While I may not be an MVC model expert, I'm trying to keep my page design separate from my logic in order to simplify things. I have already created a basic template and now I want hyperlinks to open PHP files within the same page. For example: Next ...