標籤:style blog io ar color os sp for java
伺服器返回Json格式的響應內容經常是以 String (txt) 形式返回給用戶端。用戶端需要把 文本形式的內容還原為Json格式以進一步做處理(如,取得返回內容的一個值作為下個請求的一個輸入)。這就要用到 一個函數 evel()。 具體做法如下: Parsing the JSON Response1. In the InitAgenda() function in the Agenda, define the global variable values of the SaveSource property as follows:
function InitAgenda()
{
wlGlobals.SaveSource = true
}
This instructs WebLOAD to store the complete HTML source code downloaded in the document.wlSource object. 2. Drag the JavaScript object Building Block from the Toolbox to the Agenda Tree. In the Building Block, add a function that receives the document.wlSource object and manipulates it to retrieve the statistics. The script is as follows: function evalResponse (source) { json_response = eval("(" + source + ")")} 3. Call the evalResponse function to parse the response contents:evalResponse(document.wlSource); ---------------------------------------具體做法是:------------------------------- 1. 把解析JSON 的函數 提取出來 放在一個單獨的parseJSON.js檔案裡,以便重複利用:function parseJSON(source){ jsonResponse = eval("(" + source + ")"); return jsonResponse;} 2. 在指令碼裡引進 parseJSON.js 檔案:function InitAgenda(){ wlGlobals.SaveSource = true; IncludeFile("FunctionLib\\parseJSON.js"); //IncludeFile 引進的檔案是相對指令碼wlp檔案的位置;即這裡的 Function檔案夾和wlp檔案是放在同一個根目錄下的} 3. 直接引用parseJSON 檔案裡的函數: var loginResponse = document.wlSource;var loginObj = parseJSON(loginResponse);var advisorId = loginObj.AdvisorId; 當然也可以不需要引進外部檔案,而是直接把 eval()函數放在指令碼裡 註:JSON 節點的讀取,如果是{}結構則 直接 a.b, 如果是[], 則 c[index].d 如下面是一個返回的總結構:
{ "ReturnVsBenchmark": {}, "RiskReward": {}, "Portfolios": {}, "Information": {}}
展開上面Portfolios 的階層如下:
"Portfolios": { "Id": "Portfolios", "Label": "Portfolios", "Columns": [], "Sections": [ {}, {}, { "Rows": [ { "Id": "95646f0f-879d-448b-8bf3-c9bcb15bedd0", "Status": "Actual", "OneYear": 0.13786034, "ThreeYear": 0.14883958, "FiveYear": 0.13716583, "TenYear": 0.11452207, "TrailingAsOfDate": "2014-10-31", "MarketValue": 124809.13719108, "MarketValueCurrencyCode": "USD", "ThreeYearStdDev": 10.08655991, "ThreeYearMean": 0.14883958, "RiskRewardAsOfDate": "2014-10-31", "AccountName": "Portfolio 1", "YTD": 0.09898687, "ReturnDate": "2014-10-31" }, {}, {} ] }, {}, {} ] },
要取得 "Id"的值"95646f0f-879d-448b-8bf3-c9bcb15bedd0" ,則讀取的指令碼如下:
var clientResponse = document.wlSource; // 把 返回的內容存放一個變數中var clientObj = eval( "(" + clientResponse + ")" ); // 把返回的txt 格式的內容轉化為JSON 格式var portfolioId1 = clientObj.Portfolios.Sections[2].Rows[0].Id; //Sections[2]取得是Rows 這個對象,在Sections[]裡, 每個{}對象都是Sections 對象數組的一個元素
WebLoad 解析伺服器返回的JSON格式內容