我是JSON
的新人,我真的不知道如何从内心对象中获取价值。
现在我需要得到"描述"来自JSON
对象响应的值。
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."}}}}}}
http://www.jsoneditoronline.org/?id=2ce7ac5f329bd18f06000788ba7946dc
期待结果:
邮政编码95472对FL美国无效。
示例代码:
success : function(response)
{
//alert("response="+response);
alert("Description="+Fault.detail.Errors.ErrorDetail.PrimaryErrorCode.Description);
}
答案 0 :(得分:2)
可以使用JSON.parse()
方法解析JSON字符串,并使用String#match
方法从字符串中获取数字。
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]);

如果你有一个有效的js对象(可能已被解析),则无需再次解析它。
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]);