Convert PostgreSQL text array format to JSON format PostgreSQL format: {1,2,3} or {"a","b","c"} JSON format: [1,2,3] or ["a","b","c"]
(pg_array: &str)
| 185 | /// PostgreSQL format: {1,2,3} or {"a","b","c"} |
| 186 | /// JSON format: [1,2,3] or ["a","b","c"] |
| 187 | fn pg_array_to_json(pg_array: &str) -> Result<String, String> { |
| 188 | let trimmed = pg_array.trim(); |
| 189 | |
| 190 | // If it's already JSON format, return as-is |
| 191 | if trimmed.starts_with('[') && trimmed.ends_with(']') { |
| 192 | return Ok(trimmed.to_string()); |
| 193 | } |
| 194 | |
| 195 | // Must be PostgreSQL format |
| 196 | if !trimmed.starts_with('{') || !trimmed.ends_with('}') { |
| 197 | return Err(format!("Invalid array format: {}", pg_array)); |
| 198 | } |
| 199 | |
| 200 | // Extract the content between { and } |
| 201 | let inner = &trimmed[1..trimmed.len()-1]; |
| 202 | |
| 203 | // Handle empty array |
| 204 | if inner.is_empty() { |
| 205 | return Ok("[]".to_string()); |
| 206 | } |
| 207 | |
| 208 | let mut json_elements = Vec::new(); |
| 209 | let mut current = String::new(); |
| 210 | let mut in_quotes = false; |
| 211 | let mut escape_next = false; |
| 212 | |
| 213 | for ch in inner.chars() { |
| 214 | if escape_next { |
| 215 | current.push(ch); |
| 216 | escape_next = false; |
| 217 | continue; |
| 218 | } |
| 219 | |
| 220 | if ch == '\\' && in_quotes { |
| 221 | escape_next = true; |
| 222 | current.push(ch); |
| 223 | continue; |
| 224 | } |
| 225 | |
| 226 | if ch == '"' { |
| 227 | in_quotes = !in_quotes; |
| 228 | current.push(ch); |
| 229 | } else if ch == ',' && !in_quotes { |
| 230 | // End of element |
| 231 | let elem = current.trim(); |
| 232 | if elem == "NULL" { |
| 233 | json_elements.push("null".to_string()); |
| 234 | } else if elem.starts_with('"') && elem.ends_with('"') { |
| 235 | // Already quoted string |
| 236 | json_elements.push(elem.to_string()); |
| 237 | } else { |
| 238 | // Numeric or boolean value |
| 239 | json_elements.push(elem.to_string()); |
| 240 | } |
| 241 | current.clear(); |
| 242 | } else { |
| 243 | current.push(ch); |
| 244 | } |