1

Error message is showing like below.

"{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}" 

How do I extract errorCode from above in javascript?

2 Answers 2

2

You can parse the error message to an object and then select the errorCode:

const errorMessage = "{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}"; const errorMessageObject = JSON.parse(errorMessage); const errorCode = errorMessageObject.errorCode; console.log(errorCode)

Sign up to request clarification or add additional context in comments.

Comments

0

This is a JSON encoded object. In order to access the properties of the encoded object, you need to json decode it first. You can use JSON.parse(). Then you can get its properties simply by property name.
Eg:

let encodedString = "{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}"; let decodedObj = JSON.parse(encodedString); console.log(decodedObj.errorCode); // prints "2029" 

You can use parseInt() to extract the error code as a number rather than a string. Eg:

console.log(parseInt(decodedData.errorCode)); // prints 2029 

1 Comment

Please note that JSON isn't always an encoded object. 1 is valid JSON, so is "Hello".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.