2013-12-10 10 views
2

我試圖使用PhantomJS在飛行中加載一些cookie,但出現一些錯誤。這裏是我的代碼:無法在JSON中的Phantomjs中添加cookie

上面的代碼拋出以下異常:

incompatible type of argument(s) in call to addCookie(); candidates were 
    addCookie(QVariantMap) 

我敢肯定,這裏有一個簡單的解決方案,但我有一個大腦凍結。我的印象是JSON.stringify從JSON對象返回一個字符串。令人困惑的是,當我將它打印到控制檯時,它看起來與將它存儲爲String完全相同。我的數據是這樣的:

{"domain": ".sweatytacobo.com", 
"expires": "Tue, 10 Jun 2014 16:37:46 GMT", 
"expiry": , 
"httponly": false, 
"name": "__utmz", 
"path": "/", 
"secure": false, 
"value": "268881515.13222266.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"} 

而且當我使用上面的字符串時,它添加沒有問題。那麼爲什麼我的JSON.Stringify會給我帶來問題?

編輯:

按照PhantomJS source code的addCookie的意見傳遞的格式QVariantMap:

{ 
    * "name"  : "cookie name (string)", 
    * "value" : "cookie value (string)", 
    * "domain" : "cookie domain (string)", 
    * "path"  : "cookie path (string, optional)", 
    * "httponly" : "http only cookie (boolean, optional)", 
    * "secure" : "secure cookie (boolean, optional)", 
    * "expires" : "expiration date (string, GMT format, optional)" 
    * } 

所以我不應該是能夠以某種方式傳遞一個JSON對象?

回答

3

好吧,我想通了。 PhantomJS addCookie對cookie的格式非常挑剔。

基本上爲了轉換JSON,你必須通過遍歷JSON對象來拉取值。例如:

var cookieJson = require('cookiefile.json'); 
// load in the cookies in JSON format from file 

for(var i = 0; i< cookieJson.length; i++) { 
    var tempCookie = {}; 

    tempCookie["name"] = cookieJson[i]["name"]; 
    tempCookie["domain"] = cookieJson[i]["domain"]; 
    tempCookie["value"] = cookieJson[i]["value"]; 
    tempCookie["path"] = cookieJson[i]["path"]; 
    tempCookie["session"] = cookieJson[i]["session"]; 
    tempCookie["storeId"] = cookieJson[i]["storeId"]; 

    // Here we are adding the relevant values as needed and in the proper format 

    var tempADD = {"domain": tempCookie["domain"], 
    "expires": tempCookie["expires"], 
    "expirationDate": 1402418266, 
    "httpOnly": tempCookie["httpOnly"], 
    "name": tempCookie["name"], 
    "path": tempCookie["path"], 
    "secure": tempCookie["secure"], 
    "value": tempCookie["value"], 
    "session": tempCookie["session"], 
    "storeId": tempCookie["storeId"]}; 

    // Finally, we add the cookie. phantom.addCookie returns true if successful 
    if(phantom.addCookie(tempADD)){ 
     console.log("Cookie Added!"); 
     } else { 
     console.log("Cookie Failure: "); 
     console.log(JSON.stringify(tempADD)) // print the cookie which failed to load 
     }; 
    } 
0

你有實際分配對象的字符串化版本回變量:

temp = JSON.stringify(temp); 
+0

是的,我忘了這個。但是當我添加這行代碼時,它仍然會拋出異常。 –