Add a brick to build Chinese knowledge base — The University of Science and Technology of China does not return

Problem description

You’re a mature language, and you need to be able to handle JSON data.

The solution

CJson

Use the off-the-shelf Wheel CJson library to process JSON data.

Parse the JSON structure from the string

/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
cJSON *cJSON_Parse(const char *value);// Get the CJSON object from the given JSON string
Copy the code

increase

/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);

CJSON_PUBLIC(cJSON*)cJSON_AddNumberToObject(cJSON *const object, const char *const name, const double number);

CJSON_PUBLIC(cJSON*)cJSON_AddStringToObject(cJSON *const object, const char *const name, const char *const string);
Copy the code

Add a child to an array type:

/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
Copy the code

delete

/* Delete a cJSON entity and all subentities. */
void   cJSON_Delete(cJSON *c);// Delete the cJSON object to free up the memory occupied by the linked list
Copy the code

change

CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem);
Copy the code

check

/* Get item "string" from object. Case insensitive. */
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);// Get the corresponding value based on the key (cJSON object)
Copy the code

Code sample

The source code

void print_my_json(cJSON *root) {
    // Prints the innermost key-value pairs of JSON recursively
    //Recursively print the innermost key-value pair of json
    printf("\n");

    for (int i = 0; i < cJSON_GetArraySize(root); i++) {
        // Iterate over the outermost JSON key-value pairs
        cJSON *item = cJSON_GetArrayItem(root, i);
        switch (item->type) {
            case cJSON_Object: {
                print_my_json(item);
            }
                break;
            case cJSON_Number: {
                // If the value is not a JSON object, print the key and value - numeral -int
                printf("%s->%d\n", item->string, item->valueint);
            }
                break;
            case cJSON_String: {
                // If the value is not a JSON object, print the key and value - string directly
                printf("%s->%s\n", item->string, item->valuestring);
            }
                break;
            case cJSON_Array: {
                printf("What is the array type :%s->\n", item->string);
            }
                break;
            default: {
                printf("Unprocessed type :%s->\n", item->string);
            }
                break; }}}char *json_load(char *filepath) {
    FILE *fp;
    long len;
    char *content;

    fp = fopen(filepath, "rb");
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    content = (char *) malloc(len + 1);
    fread(content, 1, len, fp);

    fclose(fp);

    return content;
}

void print_json_file(char *filepath) {
    // Read the contents from the file into the buffer
    char *json_str = json_load(filepath);
    //printf("%s\n", json_str);

    // Parse the JSON structure from the buffer
    cJSON *json = cJSON_Parse(json_str);

    print_json(json);

    //delete cjson
    cJSON_Delete(json);
}

void create_demo_json_file(char *filepath) {
    char *raw = "{"RW":"2021Annual sewer maintenance","FX":"North and south direction","DD":"Xinghu Street, industrial park328No.","RQ":"""2021years08month10No.","QS":"#WS504","ZZ":"#WS506","GJ":"300mm","GC":"Corrugated pipe","LX":"""The sewer","DW":"Suzhou XX Pipeline Testing Technology Co., LTD","YU":"Alex"}";

    // Parse the JSON structure from the JSON string
    cJSON *json = cJSON_Parse(raw);

    // Convert the incoming JSON structure to a string and print it
    char *buf = cJSON_Print(json);
    printf("raw json:\n%s\n", buf);

    // Change the value of an item
    cJSON_ReplaceItemInObject(json, "YU", cJSON_CreateString("Blex"));
    buf = cJSON_Print(json);
    printf("modified json:\n%s\n", buf);

    // Open a file and write the JSON content
    FILE *fp = fopen(filepath, "w");
    fwrite(buf, strlen(buf), 1, fp);

    fclose(fp);
    free(buf);
    cJSON_Delete(json);
}

int main(a) {
    printf("Hello, World! \n");

    // Create a file containing json data
    create_demo_json_file("jiance.json");
    // Read the file and print it
    print_json_file("jiance.json");

    return 0;
}
Copy the code

Running effect

Refer to the article

  1. Use cJSON in detail
  2. C uses cJSON to parse JSON characters
  3. # cjson read json file _json file parsing
  4. C handles JSON strings
  5. Modify the value of the JSON object and save it