用c写一个函数 传入 keys和values数组,输出json字

2023-02-13  本文已影响0人  Hamiltonian

用c写一个函数 传入 keys和values数组,输出json字符串

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* create_json_string(const char** keys, const char** values, int count)
{
    int length = 0;
    for (int i = 0; i < count; i++) {
        length += snprintf(NULL, 0, "\"%s\":\"%s\",", keys[i], values[i]);
    }
    length += snprintf(NULL, 0, "{}");
    char *json_string = (char*)malloc(length);
    memset(json_string, 0, length);
    strcat(json_string, "{");
    for (int i = 0; i < count; i++) {
        strcat(json_string, "\"");
        strcat(json_string, keys[i]);
        strcat(json_string, "\":\"");
        strcat(json_string, values[i]);
        strcat(json_string, "\"");
        if (i != count - 1) {
            strcat(json_string, ",");
        }
    }
    strcat(json_string, "}");
    return json_string;
}

int main(void)
{
    const char* keys[] = {"name", "age", "city"};
    const char* values[] = {"John", "30", "New York"};
    int count = sizeof(keys) / sizeof(keys[0]);
    char *json_string = create_json_string(keys, values, count);
    printf("%s\n", json_string);
    free(json_string);
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读