Reputation: 727
Error message is showing like below.
"{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}"
How do I extract errorCode from above in javascript?
Upvotes: 1
Views: 1228
Reputation: 39
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
Upvotes: 0
Reputation: 31331
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)
Upvotes: 2