Rama Lingam Rama Lingam - 1 month ago 6
jQuery Question

How to get value from a JSON object?

I am a new of

JSON
and really I don't know how to get value from inner object.
Now I need to get the "Description" value from
JSON
object response.

JSON Data:

{"Fault":{"faultcode":"Client", "faultstring":"An exception has been raised as a result of client data.", "detail":{"Errors":{"ErrorDetail":{"Severity":"Hard", "PrimaryErrorCode":{"Code":"111285", "Description":"The postal code 95472 is invalid for FL United States."}}}}}}


http://www.jsoneditoronline.org/?id=2ce7ac5f329bd18f06000788ba7946dc

Expecting Result:

The postal code 95472 is invalid for FL United States.

Sample Code:

success : function(response)
{
//alert("response="+response);
alert("Description="+Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description);
}

Answer

The JSON string can be parsed using JSON.parse() method and use String#match method to get the number from the string.

var json = '{"Fault":{"faultcode":"Client", "faultstring":"An exception has been raised as a result of client data.", "detail":{"Errors":{"ErrorDetail":{"Severity":"Hard", "PrimaryErrorCode":{"Code":"111285", "Description":"The postal code 95472 is invalid for FL United States."}}}}}}'

console.log("Description=" + JSON.parse(json).Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description.match(/\d+/)[0]);


If you had a valid js object(may be already parsed) then there is no need to parse it again.

var obj = {"Fault":{"faultcode":"Client", "faultstring":"An exception has been raised as a result of client data.", "detail":{"Errors":{"ErrorDetail":{"Severity":"Hard", "PrimaryErrorCode":{"Code":"111285", "Description":"The postal code 95472 is invalid for FL United States."}}}}}};

console.log("Description=" + obj.Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description.match(/\d+/)[0]);

Comments