C數據生成JSON文件
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,常用于Web應用程序中的數據傳輸。
C語言是一種高效且廣泛使用的編程語言,可以用它來生成JSON格式的數據文件。
下面介紹一個使用C語言來生成JSON文件的示例程序:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_JSON_DATA 100 int main(int argc, char *argv[]) { // 定義需要轉換為JSON數據的C結構體 struct person { char *name; int age; char *address; } p[] = { {"Alice", 23, "New York"}, {"Bob", 28, "Los Angeles"}, {"Cathy", 35, "Chicago"}, {"David", 40, "San Francisco"}, {NULL, 0, NULL} // 結束標志 }; char json_data[MAX_JSON_DATA]; int offset = 0; // 開始創建JSON數據格式的字符串 offset += sprintf(json_data + offset, "{\n"); offset += sprintf(json_data + offset, " \"persons\": [\n"); struct person *p_item = p; while (p_item->name != NULL) { offset += sprintf(json_data + offset, " {\n"); offset += sprintf(json_data + offset, " \"name\": \"%s\",\n", p_item->name); offset += sprintf(json_data + offset, " \"age\": %d,\n", p_item->age); offset += sprintf(json_data + offset, " \"address\": \"%s\"\n", p_item->address); offset += sprintf(json_data + offset, " },\n"); p_item++; } offset -= 2; // 刪除最后一個逗號和回車 offset += sprintf(json_data + offset, "\n ]\n}"); printf("JSON data:\n%s\n", json_data); // 將JSON數據寫入文件 FILE *fp; fp = fopen("sample.json", "w"); if (fp == NULL) { printf("Failed to open file sample.json\n"); exit(1); } fputs(json_data, fp); fclose(fp); return 0; }
運行上述程序后,在當前目錄下會生成一個sample.json文件,內容如下:
{ "persons": [ { "name": "Alice", "age": 23, "address": "New York" }, { "name": "Bob", "age": 28, "address": "Los Angeles" }, { "name": "Cathy", "age": 35, "address": "Chicago" }, { "name": "David", "age": 40, "address": "San Francisco" } ] }