Serialize the result batch as JSON (for pgwire/REST response). Returns a JSON array of objects: `[{"node_id": "alice", "rank": 0.42}, ...]`. Used by tests; production code uses `to_msgpack()` + `decode_payload_to_json()`.
(&self)
| 166 | /// Returns a JSON array of objects: `[{"node_id": "alice", "rank": 0.42}, ...]`. |
| 167 | /// Used by tests; production code uses `to_msgpack()` + `decode_payload_to_json()`. |
| 168 | pub fn to_json(&self) -> Result<Vec<u8>, crate::Error> { |
| 169 | let schema = self.algorithm.result_schema(); |
| 170 | let mut rows = Vec::with_capacity(self.row_count); |
| 171 | |
| 172 | for row_idx in 0..self.row_count { |
| 173 | let mut obj = serde_json::Map::new(); |
| 174 | for (col_idx, &(col_name, _col_type)) in schema.iter().enumerate() { |
| 175 | let (col_type, vec_idx) = self.column_map[col_idx]; |
| 176 | let val = match col_type { |
| 177 | AlgoColumnType::Text => { |
| 178 | serde_json::Value::String(self.text_columns[vec_idx][row_idx].clone()) |
| 179 | } |
| 180 | AlgoColumnType::Float64 => { |
| 181 | serde_json::json!(self.f64_columns[vec_idx][row_idx]) |
| 182 | } |
| 183 | AlgoColumnType::Int64 => { |
| 184 | serde_json::json!(self.i64_columns[vec_idx][row_idx]) |
| 185 | } |
| 186 | }; |
| 187 | obj.insert(col_name.to_string(), val); |
| 188 | } |
| 189 | rows.push(serde_json::Value::Object(obj)); |
| 190 | } |
| 191 | |
| 192 | sonic_rs::to_vec(&rows).map_err(|e| crate::Error::Internal { |
| 193 | detail: format!("json serialization: {e}"), |
| 194 | }) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl zerompk::ToMessagePack for AlgoResultBatch { |