簡體   English   中英

如何從JSON對象獲取價值?

[英]How to get value from a JSON object?

我是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對美國佛羅里達州無效。

樣例代碼:

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

可以使用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]); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM