Ramalingam Perumal
Ramalingam Perumal

Reputation: 1427

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);    
        }

Upvotes: 1

Views: 150

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115272

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]);

Upvotes: 2

Related Questions