Is there a way for me to retrieve the value associated with a specific key within this JSON object?

Looking to extract the error message from _body.

My current method involves:

console.log(message._body.error);

Unfortunately, this returns undefined.

If I try console.log(message._body);

I receive "{"code":141,"error":"This phone number exists already!"}"

var message = {  
"_body":"{"code":141,"error":"This phone number exists already!}",
"status":400,
"ok":false,
"statusText":"Bad Request",
"type":2
};

Note: The backend provides the following format and it cannot be altered or quotes removed

   "_body":"{"code":141,"error":"This phone number exists already!"}"

Any suggestions on how to access the error message?

Answer №1

It appears that there is a value stored in your property which comprises a valid JSON string.

To transform this into an object, you will have to utilize the JSON.parse() method.

Answer №2

If you encounter an error from your backend, make sure to handle it appropriately by converting it to JSON using the json() method.

You can try the following solution:

error.json().error

console.log(error.json().error)

Answer №3

Eliminate the use of double quotation marks. Follow these instructions...

"_body":{"code":141,"error":"This phone number is already in use!"},

Check out this code snippet...

https://jsfiddle.net/cmht6u8f/1/

Answer №4

  1. Ensure the JSON is correctly formatted:

    var response = { 
        "_body":'{"code":141,"error":"This phone number exists already!"}',
        "status":400,
        "ok":false,
        "statusText":"Bad Request",
        "type":2
     };
    
  2. Extract and utilize the data from the nested JSON...

     var errorDetails = JSON.parse(response._body);
     console.log(errorDetails.error);
    

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

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

VueJS encounters a missing Grpc-Web module

I have just finished setting up a VueJS application that includes TypeScript functionality. After running the command: protoc -I=. service.proto --js_out=import_style=typescript:. --grpc web_out=import_style=typescript,mode=grpcwebtext:. I now have the ...

What is the best way to extract JSON data from an HTML file and store it into a Python

My goal is to extract structured data from a JSON statement embedded in an HTML page. To achieve this, I extracted the HTML content and obtained the JSON using XPath: json.loads(response.xpath('//*[@id="product"]/script[2]/text()').extract_first ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

Having trouble bringing my custom-built Angular module into my Angular application

Currently considering the utilization of this Yeoman generator as a starting point for a small project that will contain several reusable form components to be published. The generator constructs a module and an example component, directive, pipe, and serv ...

Leveraging JavaScript to change the input value by appending the character "#"

I am looking to modify the input value by adding a "#" in front of each word, but I am facing issues with handling spaces properly. function addHash(input) { var text = input.value.replace('#', ''); var words = text.split(" "); ...

Extracting Azure table storage continuation tokens using Node.js

I am currently working on incorporating continuation tokens in Azure table storage by referencing the following link, https://learn.microsoft.com/en-us/azure/cosmos-db/table-storage-how-to-use-nodejs Here is the code snippet I am using: var nextContinuat ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

Navigating a page without embedding the URL in react-router-dom

In my application, I am utilizing react-router-dom v5 for routing purposes. Occasionally, I come across routes similar to the following: checkup/step-1/:id checkup/step-2/:id checkup/step-3/:id For instance, when I find myself at checkup/step-1/:id, I int ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

What level of detail is optimal for my model?

What is the best approach for structuring data models in Meteor? For example, let's consider a data model with a XmlDocument containing multiple XmlNodes. Should I create a single collection like new Meteor.Collection("Documents") and update it as a ...

Safari is unable to display the button text, while Chrome has no problem showing it

In Safari, the text of the button is not showing up properly. I am able to retrieve the text using jQuery in the console though. However, there seems to be an issue with recognizing the click event. <div class="btn-group btn-group-lg"> <button ...

Retrieve a file from an Express API using React with the help of Axios

When working with a React client and an Express API, how can the React client download a file sent by the Express API? Issue: If I manually enter the URL into my browser's address bar and hit enter, the file downloads successfully. However, when I ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Jackson: Is it possible to update a property in a JSON without changing the corresponding POJO?

Is it possible to edit the name of an "existing field" in a POJO instead of adding an "extra_field"? I am looking for a solution that allows me to achieve this without using the @JsonProperty annotation mentioned in the link below. The requirement is to h ...

Struggles encountered while trying to post a JSON value with Spring Boot

I am currently facing an issue with making a post request using JSON in Postman. The request seems to be successful only when formatted in a specific way, like this: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43262e222a2f03 ...