Extract a string value from JSON properties_json by key. * Writes result to buf (up to buf_sz). Returns buf if found, "" otherwise. * Handles both string values ("key":"value") and numeric values ("key":1.5). */
| 2413 | * Writes result to buf (up to buf_sz). Returns buf if found, "" otherwise. |
| 2414 | * Handles both string values ("key":"value") and numeric values ("key":1.5). */ |
| 2415 | static const char *json_extract_prop(const char *json, const char *key, char *buf, size_t buf_sz) { |
| 2416 | if (!json || !key) { |
| 2417 | buf[0] = '\0'; |
| 2418 | return buf; |
| 2419 | } |
| 2420 | /* Build search pattern: "key": */ |
| 2421 | char pattern[CBM_SZ_256]; |
| 2422 | snprintf(pattern, sizeof(pattern), "\"%s\":", key); |
| 2423 | const char *p = strstr(json, pattern); |
| 2424 | if (!p) { |
| 2425 | buf[0] = '\0'; |
| 2426 | return buf; |
| 2427 | } |
| 2428 | p += strlen(pattern); |
| 2429 | /* Skip whitespace */ |
| 2430 | while (*p == ' ' || *p == '\t') { |
| 2431 | p++; |
| 2432 | } |
| 2433 | if (*p == '"') { |
| 2434 | /* String value — honor backslash escapes: without this, an embedded \" |
| 2435 | * cuts the value short at the first escaped quote. */ |
| 2436 | p++; |
| 2437 | size_t i = 0; |
| 2438 | while (*p && *p != '"' && i < buf_sz - SKIP_ONE) { |
| 2439 | if (*p == '\\' && p[SKIP_ONE] && i + SKIP_ONE < buf_sz - SKIP_ONE) { |
| 2440 | buf[i++] = *p++; /* keep the escape pair intact */ |
| 2441 | } |
| 2442 | buf[i++] = *p++; |
| 2443 | } |
| 2444 | buf[i] = '\0'; |
| 2445 | } else if (*p == '[' || *p == '{') { |
| 2446 | /* Array/object value — copy the whole balanced construct. A scan-to-comma |
| 2447 | * truncates at the first comma INSIDE the value: e.g. a decorators array |
| 2448 | * ["@Roles('OWNER', 'ADMIN')","@Get()"] came back as ["@Roles('OWNER'. */ |
| 2449 | char open = *p; |
| 2450 | char close = (open == '[') ? ']' : '}'; |
| 2451 | int depth = 0; |
| 2452 | int in_str = 0; |
| 2453 | size_t i = 0; |
| 2454 | while (*p && i < buf_sz - SKIP_ONE) { |
| 2455 | char c = *p; |
| 2456 | if (in_str) { |
| 2457 | if (c == '\\' && p[SKIP_ONE] && i + SKIP_ONE < buf_sz - SKIP_ONE) { |
| 2458 | buf[i++] = *p++; /* escape pair stays intact */ |
| 2459 | } else if (c == '"') { |
| 2460 | in_str = 0; |
| 2461 | } |
| 2462 | } else if (c == '"') { |
| 2463 | in_str = 1; |
| 2464 | } else if (c == open) { |
| 2465 | depth++; |
| 2466 | } else if (c == close) { |
| 2467 | depth--; |
| 2468 | } |
| 2469 | buf[i++] = *p++; |
| 2470 | if (!in_str && depth == 0) { |
| 2471 | break; /* outer bracket closed */ |
| 2472 | } |