我是json-c的新手。
我能够以以下格式创建JSON对象:
{"loglevel":"INFO", "msg":"Info about car", "timestamp":"actual system time"}
但是我需要帮助创建格式为的JSON对象
{"module":"log","version":1.0, "logs":[{"loglevel":"INFO", "msg":"Info about car", "timestamp":"actual system time"}]}
代码如下:
/*Line is the messge of string which is passed from other module*/
static void json_file(char *line)
{
FILE* lg;
lg = fopen(JSON_FILE,"ab+");
char *json = "{"key1":"data", "key2":1.0, "Logs":[";
fwrite(line, sizeof(char), strlen(line),lg);
fputs("]}", lg);
/*replace last ']}' with ',' json string and ]} */
char stringtofind[4] = "]}";
char get_line[2000];
fgets(get_line, sizeof(get_line), lg);
if (strstr(get_line, stringtofind) != NULL)
{
printf("substring found n");
/* Help Required here*/
/* please help */
// Need to replace the "]}" into ","
}
}
据我所知,您想要使用json-c,对吧?那为什么不使用真正的语法呢?
#include <stdio.h>
#include <json-c/json.h>
json_object *generate_log_object(char *log_level, char *msg, char *timestamp){
// {}
json_object *child = json_object_new_object();
// {"loglevel": ... }
json_object_object_add(child, "loglevel", json_object_new_string(log_level));
// {"loglevel":"...", "msg":"..."}
json_object_object_add(child, "msg", json_object_new_string(msg));
// {"loglevel":"...", "msg":"...", "timestamp":"..."}
json_object_object_add(child, "timestamp", json_object_new_string(timestamp));
return child
}
int main(void)
{
json_object *root = json_object_new_object();
if (!root)
return 1;
// {"module":"log"}
json_object_object_add(root, "module", json_object_new_string("log"));
// {"module":"log","version":1.0 }
json_object_object_add(root, "version", json_object_new_string("1.0"));
// {"module":"log","version":1.0, "logs":[]}
json_object *logs = json_object_new_array();
json_object_object_add(root, "logs", logs);
// {"module":"log","version":1.0, "logs":[{"loglevel":"INFO", "msg":"Info about car", "timestamp":"actual system time"}]}
char *log1 = generate_log_object("INFO", "Info about car", "system time");
json_object_array_add(children, log1);
}
顺便说一句,在过去的5年里,我没有使用过C,也从未使用过json-c
。我没有编译代码,所以可能有一些拼写错误,或者我让你修复的小错误。