1. 程式人生 > >JSON的一個整合兩個JSON對應值加合一起

JSON的一個整合兩個JSON對應值加合一起

void JSON_Integration(cJSON *tiny,cJSON *huge)
{
	 uchar Nodenum_rel ; uchar Nodenum_day;
	/* start ReNewing */
	Nodenum_rel = cJSON_GetArraySize(huge);
	Nodenum_day = cJSON_GetArraySize(tiny);

	for(uchar i =0;i<Nodenum_rel;i++)
	{
		cJSON *Node_realtime = cJSON_GetArrayItem(huge,i);
		const char *IP_rel = cJSON_GetObjectItem(Node_realtime,"IP")->valuestring;
		for(uchar j=0;j<Nodenum_day;j++)
		{
			cJSON *Node_day = cJSON_GetArrayItem(tiny,j);
			const char *IP_day = cJSON_GetObjectItem(Node_day,"IP")->valuestring;
			if(strcmp(IP_day,IP_rel)==0)
			{
				long rx_rel = cJSON_GetObjectItem(Node_realtime,"rx")->valuedouble;
				long tx_rel = cJSON_GetObjectItem(Node_realtime,"tx")->valuedouble;
				long err_rel = cJSON_GetObjectItem(Node_realtime,"err")->valuedouble;

				long rx_day = cJSON_GetObjectItem(Node_day,"rx")->valuedouble;
				long tx_day = cJSON_GetObjectItem(Node_day,"tx")->valuedouble;
				long err_day = cJSON_GetObjectItem(Node_day,"err")->valuedouble;

				rx_rel = rx_rel+rx_day ;
				tx_rel = tx_rel+tx_day ;
				err_rel = err_rel+err_day ;

				cJSON *New = cJSON_CreateObject();
				cJSON_AddStringToObject(New,"IP",IP_rel);
				cJSON_AddNumberToObject(New,"rx",rx_rel);
				cJSON_AddNumberToObject(New,"tx",tx_rel);
				cJSON_AddNumberToObject(New,"err",err_rel);

				cJSON_ReplaceItemInArray(huge,i,New);
			}
		}
	}
}

備註:程式碼的思路,遍歷一個較小的JSON的檔案,從他們之中找到相同的的標誌,這裡是IP,他們做了統計,然後依次讀出後,建立新的JSON ,最後替換。