Home > OS >  problem in parsing json in javascript and access value by key
problem in parsing json in javascript and access value by key

Time:07-30

I'm receiving some error response in 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"]);
    });

Here are outputs of console.log : enter image description here

I need to access Message but none of them create access to its value. How can I access Message?

Main Question

  1. why all of them are 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"]);

Meanwhile when I copy Response.responseText to JSON Deserialize Online, everything is fine.

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'."]}}

enter image description here

CodePudding user response:

Okay, so the problem is that Response.responseText is already a string. You don't need to do JSON.stringify(Response.responseText). Please directly, parse it to JSON and then use the object:

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

CodePudding user response:

please give us more information about your code!

  • Related