Untitled
unknown
c_cpp
10 months ago
2.0 kB
8
Indexable
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <cjson/cJSON.h> // Function to search for the key in the JSON object void search_key(cJSON *json, const char *key) { if (json == NULL) { return; } if (cJSON_IsObject(json) || cJSON_IsArray(json)) { cJSON *child = json->child; while (child) { // Compare the key with the child's key if (child->string && strcmp(child->string, key) == 0) { if (cJSON_IsString(child)) { printf("Found key: %s, Value: %s\n", child->string, child->valuestring); } else { // Convert json object to string char *json_str = cJSON_Print(child); printf("Found key: %s, Value: %s\n", child->string, json_str); } } // Continue the search recursively search_key(child, key); child = child->next; } } } int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s <json_filename> <target_key>\n", argv[0]); return 1; } const char *filename = argv[1]; const char *target_key = argv[2]; FILE *file = fopen(filename, "r"); if (file == NULL) { perror("Error opening file"); return 1; } fseek(file, 0, SEEK_END); long length = ftell(file); fseek(file, 0, SEEK_SET); char *data = (char *)malloc(length + 1); if (data == NULL) { perror("Error allocating memory"); fclose(file); return 1; } fread(data, 1, length, file); data[length] = '\0'; fclose(file); cJSON *json = cJSON_Parse(data); if (json == NULL) { printf("Error parsing JSON: %s\n", cJSON_GetErrorPtr()); free(data); return 1; } // Display the JSON object printf("JSON Object:\n%s\n", cJSON_Print(json)); search_key(json, target_key); cJSON_Delete(json); free(data); return 0; }
Editor is loading...
Leave a Comment