json数据扁平化处理(适用于接口传参复杂数据加密处理)
json数据扁平化处理(适用于接口传参复杂数据加密处理)
/* * name:json数组拉平处理 * data:json对象或者数组 * k:前面开始可传空 */ function expandJsonTool(data, k) { var jmap = {} var expandJson = function(jstr, mapIndex) { if (jstr instanceof Array) { for (var i in jstr) { expandJson(jstr[i], `${mapIndex}[${i}]`); } } else if (jstr instanceof Object) { for (var i in jstr) { // 如果mapIndex为false,null,''时,则不加初始索引 if (!mapIndex) { var key = i; } else { var key = `${mapIndex}.${i}`; } // Array 是 Object 的子集,先判断是否为 Array,如果是,则不走Object的判断 if (jstr[i] instanceof Array) { for (var j in jstr[i]) { expandJson(jstr[i][j], `${key}[${j}]`); } } else if ((jstr[i] instanceof Object)) { expandJson(jstr[i], key); } else { jmap[key] = jstr[i] } } } } expandJson(data, k); return jmap }
原始数据
{ "bandEndPrize": [{ "flag": 0, "gameId": 0, "limit": 0, "orderBy": 0, "prizeIcon": "", "prizeName": "", "prizeTime": "", "prizeType": "", "unit": "" }], "bandIngPrize": [{ "flag": 0, "gameId": 0, "limit": 0, "orderBy": 0, "prizeIcon": "", "prizeName": "", "prizeTime": "", "prizeType": "", "unit": "" }], "bandTaskRequest": [{ "addGameWeekTaskReqs": [{ "orderBy": 0, "score": 0, "taskCode": "", "taskValue": 0 }, { "orderBy": 0, "score": 0, "taskCode": "", "taskValue": 0 } ], "gameId": 0, "gameWeekEnd": "", "gameWeekId": 0, "gameWeekStart": "", "id": 0, "seaTaskType": 0, "taskType": 0 }] };
处理后的数据
{ "bandEndPrize[0].flag": 0, "bandEndPrize[0].gameId": 0, "bandEndPrize[0].limit": 0, "bandEndPrize[0].orderBy": 0, "bandEndPrize[0].prizeIcon": "", "bandEndPrize[0].prizeName": "", "bandEndPrize[0].prizeTime": "", "bandEndPrize[0].prizeType": "", "bandEndPrize[0].unit": "", "bandIngPrize[0].flag": 0, "bandIngPrize[0].gameId": 0, "bandIngPrize[0].limit": 0, "bandIngPrize[0].orderBy": 0, "bandIngPrize[0].prizeIcon": "", "bandIngPrize[0].prizeName": "", "bandIngPrize[0].prizeTime": "", "bandIngPrize[0].prizeType": "", "bandIngPrize[0].unit": "", "bandTaskRequest[0].addGameWeekTaskReqs[0].orderBy": 0, "bandTaskRequest[0].addGameWeekTaskReqs[0].score": 0, "bandTaskRequest[0].addGameWeekTaskReqs[0].taskCode": "", "bandTaskRequest[0].addGameWeekTaskReqs[0].taskValue": 0, "bandTaskRequest[0].addGameWeekTaskReqs[1].orderBy": 0, "bandTaskRequest[0].addGameWeekTaskReqs[1].score": 0, "bandTaskRequest[0].addGameWeekTaskReqs[1].taskCode": "", "bandTaskRequest[0].addGameWeekTaskReqs[1].taskValue": 0, "bandTaskRequest[0].gameId": 0, "bandTaskRequest[0].gameWeekEnd": "", "bandTaskRequest[0].gameWeekId": 0, "bandTaskRequest[0].gameWeekStart": "", "bandTaskRequest[0].id": 0, "bandTaskRequest[0].seaTaskType": 0, "bandTaskRequest[0].taskType": 0 }
愿你走出半生,归来仍是少年