请求协助:无库C语言实现JSON解析(适配实时处理及指定数据)
Since you're dealing with a fixed JSON structure (an array of objects with exactly Letter and Freq integer fields) and need a lightweight, real-time parser without third-party libraries, a tailored, minimal parser is the way to go. General-purpose JSON parsers add unnecessary overhead that's avoidable here—this implementation is fast, uses no dynamic memory allocation, and is optimized for your specific data format.
Step 1: Define the Data Structure
First, create a struct to store each parsed letter-frequency pair:
#include <stdio.h> #include <ctype.h> #include <string.h> // Struct to hold parsed letter-frequency data typedef struct { int letter; int freq; } LetterFreq;
Step 2: Helper Functions
These small utilities handle repetitive tasks like skipping whitespace and parsing integers:
// Skip whitespace characters (spaces, tabs, newlines) static void skip_whitespace(const char **json) { while (**json && isspace((unsigned char)**json)) { (*json)++; } } // Parse an integer from the JSON string static int parse_int(const char **json) { int value = 0; int sign = 1; skip_whitespace(json); // Handle negative numbers if (**json == '-') { sign = -1; (*json)++; } // Convert digit characters to integer while (**json && isdigit((unsigned char)**json)) { value = value * 10 + (**json - '0'); (*json)++; } return value * sign; }
Step 3: Main Parser Function
This function is purpose-built to parse your exact JSON structure. It avoids flexibility in favor of speed and minimal overhead:
// Parse the JSON array into an array of LetterFreq structs // Returns number of entries parsed, or -1 on error int parse_letter_freqs(const char *json, LetterFreq *output, int max_entries) { int count = 0; // Skip whitespace and check for array start skip_whitespace(&json); if (*json != '[') { return -1; // Invalid: expected array opening bracket } json++; while (count < max_entries) { skip_whitespace(&json); if (*json == ']') break; // End of array // Check for object start if (*json != '{') return -1; json++; LetterFreq entry = {0}; int has_letter = 0, has_freq = 0; // Parse key-value pairs inside the object while (1) { skip_whitespace(&json); if (*json == '}') { json++; break; // End of object } // Expect a quoted key if (*json != '"') return -1; json++; // Parse "Letter" key if (strncmp(json, "Letter", 6) == 0 && json[6] == '"') { json += 7; // Skip "Letter" and closing quote skip_whitespace(&json); if (*json != ':') return -1; json++; entry.letter = parse_int(&json); has_letter = 1; } // Parse "Freq" key else if (strncmp(json, "Freq", 4) == 0 && json[4] == '"') { json += 5; // Skip "Freq" and closing quote skip_whitespace(&json); if (*json != ':') return -1; json++; entry.freq = parse_int(&json); has_freq = 1; } else { return -1; // Unknown key (invalid for our structure) } // Skip comma between key-value pairs skip_whitespace(&json); if (*json == ',') json++; } // Ensure both required keys were found if (!has_letter || !has_freq) return -1; output[count++] = entry; // Skip comma between objects skip_whitespace(&json); if (*json == ',') json++; } // Verify array is properly closed skip_whitespace(&json); if (*json != ']') return -1; return count; }
Step 4: Usage Example
Since your JSON is generated by your own code, you can directly pass it to the parser. Here's how to use it:
int main() { // Sample JSON (replace with your generated output) const char *generated_json = "[ { \"Letter\": 0 , \"Freq\": 2858 }, { \"Letter\" : 31, \"Freq\" : 0 } ]"; // Pre-allocate output array (we know max entries is 32: 0-31) LetterFreq freq_data[32]; int entry_count = parse_letter_freqs(generated_json, freq_data, 32); if (entry_count < 0) { printf("Error parsing JSON\n"); return 1; } // Use the parsed data (example: print results) for (int i = 0; i < entry_count; i++) { printf("Letter %d: Frequency = %d\n", freq_data[i].letter, freq_data[i].freq); } return 0; }
Key Real-Time Optimizations
- No Dynamic Allocation: The output array is pre-allocated (we know there are exactly 32 letters, 0-31), eliminating heap fragmentation and unpredictable delays.
- Minimal Checks: The parser only handles your exact JSON structure, avoiding the overhead of general-purpose parsers that support all JSON features.
- Fast Execution: All operations are linear time (
O(n)) relative to the length of the JSON string.
内容的提问来源于stack exchange,提问作者ashu nath

