使用FiddlerScript的OnBeforeResponse更改数组中元素的属性

时间:2018-08-14 01:38:05

标签: arrays json fiddler jscript.net

我正在尝试编写FiddlerScript来修改从服务器返回的JSON数组的属性。

这是我到目前为止尝试过的:

static function OnBeforeResponse(oSession: Session) {
    if (m_Hide304s && oSession.responseCode == 304) {
        oSession["ui-hide"] = "true";
    }
    if(oSession.HostnameIs("myserver.com") && oSession.uriContains("info")) {
        oSession["ui-backcolor"] = "lime";

        // Convert the request body into a string
        var oBody = System.Text.Encoding.UTF8.GetString(oSession.requestBodyBytes);

        // Convert the text into a JSON object
        var j = Fiddler.WebFormats.JSON.JsonDecode(oBody);

        var placementsArray = j.JSONObject["placements"];

        FiddlerObject.log("Got Placements.");
        // I can't figure out how to access the elements of the array
        //for (var i: int=0; i < placementsArray.Length; i++) {
        //    placements[i]["isValid"] = true;
        //}

        // Convert back to a byte array
        var modBytes = Fiddler.WebFormats.JSON.JsonEncode(j.JSONObject);

        // Convert json to bytes, storing the bytes in request body
        var mod = System.Text.Encoding.UTF8.GetBytes(modBytes);
        oSession.RequestBody = mod;
    }
}

我需要在此功能中间注释掉的for循环方面的帮助。我想遍历“展示位置”的数组,然后在每个这些“展示位置”对象中更改一个名为“ IsValid”的值。我需要这样做,以便可以修改来自服务器的响应,以便可以针对数组项属性值用不同的服务器响应来测试客户端应用程序。

1 个答案:

答案 0 :(得分:0)

如果有帮助,这里是答案。我错误地获取并设置了 Request 正文而不是 Response 正文,并且我还使用了ArrayList的“ Length”属性,而不是“ Count”。

static function OnBeforeResponse(oSession: Session) {
    // This code was already here, leaving it
    if (m_Hide304s && oSession.responseCode == 304) {
        oSession["ui-hide"] = "true";
    }
    // Here is new code to modify server's response
    if(oSession.HostnameIs("myserver.com") && oSession.uriContains("info")) {
        // Color this response, so we can spot it in Fiddler
        oSession["ui-backcolor"] = "lime";

        // Convert the request body into a string
        var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);

        var j: Fiddler.WebFormats.JSON.JSONParseResult;
        // Convert the text into a JSON object
        // In this case our JSON root element is a dictionary (HashTable)
        j = Fiddler.WebFormats.JSON.JsonDecode(oBody);

        // Inside of our dictionary, we have an array (ArrayList) called "placements"
        var placementsArray = j.JSONObject["placements"];
        for (var iEach = 0; iEach < placementsArray.Count; iEach++){
            // In each object/member in the array, we change one of its properties
            placementsArray[iEach]["isValid"] = true;
        }

        // Convert back to a byte array
        var modBytes = Fiddler.WebFormats.JSON.JsonEncode(j.JSONObject);

        // Convert json to bytes, storing the bytes in request body
        var mod = System.Text.Encoding.UTF8.GetBytes(modBytes);
        oSession.ResponseBody = mod;
    }
}