Difficulty with parsing JSON in JavaScript and retrieving values by key

I'm encountering an error response within the ajax error function;

    $.ajax(Request).error(function (Response) {
        var content = JSON.stringify(Response.responseText);
        var obj = JSON.parse(content);
        console.log("Response.responseText:",Response.responseText);
        console.log("Response.responseText.Message:", Response.responseText.Message);
        console.log("Response.responseText[Message]:", Response.responseText["Message"]);
        console.log("content:", content);
        console.log("content.Message:", content.Message);
        console.log("content[Message]:", content["Message"]);
        console.log("obj:", obj);
        console.log("obj.message:", obj.Message);
        console.log("obj[Message]:", obj["Message"]);
    });

The results from console.log are shown here : https://i.sstatic.net/4g00N.jpg

I am trying to retrieve Message but have not been successful in accessing its value. How can I access Message?

Main Question

  1. why are all of them showing as undefined?
  2. How can I access Message?

Solution

        var parsed= JSON.parse(startpaymentResponse.responseText);
        console.log("parsed:", parsed);
        console.log("parsed.Message:", parsed.Message);
        console.log("parsed[Message]:", parsed["Message"]);

In the meantime, when I paste Response.responseText into JSON Deserialize Online, everything works correctly.

Response.responseText: {"Message":"The request is invalid.","ModelState":{"model.Amount":["The field Amount must be a string or array type with a minimum length of '4'."],"model.TotalAmount":["The field TotalAmount must be a string or array type with a minimum length of '4'."]}}

https://i.sstatic.net/umbUK.jpg

Answer №1

The issue at hand arises from the fact that Response.responseText is already a string. Avoid unnecessary steps by skipping

JSON.stringify(Response.responseText)
. Instead, move straight to parsing it as JSON and utilizing the object:

$.ajax(Request).error(function (Response) {
  var obj = JSON.parse(Response.responseText);
  console.log("obj.Message", obj.Message);
});

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

PHP - Is it possible to transfer the name of a POST method from one page to another in PHP?

How can I retrieve and check the value of a select option from one page to another using PHP? Specifically, I want to access the POST name ($_POST['selection_value']) and validate if it matches a certain selection value (e.g., 'time'). ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

Having trouble retrieving specific data with curl

Trying to retrieve specific data using cURL from the website . The following code is used to fetch all data: <?php $url='http://dummy.restapiexample.com/api/v1/employees'; $my_curl = curl_init(); curl_setopt($my_curl, CURLOPT_URL, $url); curl ...

JavaScript is proving to be uncooperative in allowing me to modify the

Despite searching through previously asked questions, I have been unable to find a solution to my issue. I am struggling with changing an image source upon clicking the image itself. The following is a snippet of my HTML code: <img id="picture1" oncli ...

Encountering an Issue while Importing JSON Data with mongoimport in MongoDB

Hello there, I've been attempting to import a JSON file into my mongodb collection but am encountering an error. Can someone guide me on how to successfully import this json file? I have tried using both mongodb compass and mongoshell but unfortunatel ...

Steps for updating the nested array object using the unique identifier: "id"

Having trouble updating the nested state array in my module where users scan QR codes to update tracking numbers. Currently, I am using react js for frontend and Laravel for backend. Issue: When scanning the QR code, the tracking number is not being set t ...

Product pages created with PHP, such as displaying as: Page: [1] 2 3 4

I am working on a product page created with WordPress that fetches products and displays them. However, I want to restrict the number of products visible at once. Code for generating with WordPress/PHP: $pages = get_pages(array('parent' => $ ...

What is preventing me from utilizing my JavaScript constructor function externally?

I have a question about how I create my object: var myViewModel = new MyViewModel("other"); Why am I unable to call myViewModel.setHasOne(value) from outside the viewmodel? Whenever I try, I encounter this error message: Uncaught TypeError: Cannot ca ...

The applet is smooth and functional when executed from Eclipse, but experiences difficulties when launched in a web browser

Hey there, I’m dealing with a bit of an issue involving a Java applet and could really use some assistance. Here's the situation: I attempted to create an applet that connects to digg.com using its API to display the 100 most popular stories, comple ...

Setting an if isset statement below can be achieved by checking if the variable

I have included a javascript function below that is designed to display specific messages once a file finishes uploading: function stopImageUpload(success){ var imagename = <?php echo json_encode($imagename); ?>; var result = '& ...

Issues surrounding the determination of CSS attribute value using .css() function within a variable

I have been working on a function to change the color of a span dynamically from black to a randomly selected color from a predefined list. However, I am encountering an issue with the .css("color", variableName) part of my code and suspect that my synta ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

JavaScript causing Axios network error

Recently, I've started exploring the combination of axios and stripe in my project but unfortunately, I have encountered some challenges. Whenever I attempt to initiate a post request using axios, an error pops up which looks like this: https://i.sta ...

Before installing npm packages, ensure to gracefully stop the process during pre-installation

Is there a way to stop the npm install process conditionally within a preinstall script? At the moment, I have a preinstall script named preinstall.js: if (someCondition) { process.kill(process.ppid, 'SIGKILL'); } The content of my package.js ...

Troubleshooting issues with sending data from Node.js to MongoDB

I recently started learning nodeJS and I'm facing an issue with sending data from a register form to mongodb. It seems like I made a mistake while using the post method, as I am unable to see the data on postman. const express = require('express& ...

Can you explain the distinction between angular-highcharts and highcharts-angular?

Our team has been utilizing both angular-highcharts and highcharts-angular in various projects. It appears that one functions as a directive while the other serves as a wrapper. I'm seeking clarification on the distinctions between the two and recomme ...

turn the cube shape into one with smooth, rounded corners

Does anyone know how to create a cube with rounded corners using three.js? I've heard it's not possible with CSS. Any guidance on how to achieve this? Check out this link for an example /* |------------------------------------------| | MelonHTM ...

Pass a JSON string to a C# function

Within my ASP.NET page, there exists an important method: public static void UpdatePage(string accessCode, string newURL) { HttpContext.Current.Cache[accessCode] = newURL; } The purpose of this method is to update the Cache based on the provided acce ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

Issues with webpage responsiveness, width not adjusting correctly

Just completed coding my website and now I'm facing a new challenge. I am focusing on making it responsive for tablet screens (768px) starting with the header section, but for some reason, the modifications I make in the responsive.css file are not ta ...