【发布时间】:2019-04-12 17:41:14
【问题描述】:
我有一个 bash 脚本,它以 Hostname IP MacAddr 格式输出字符串,并由我用 C 语言编写的脚本读取。我正在尝试将这 3 个拆分为一个数组,并使其成为能够将它们存储到 Json-c 对象中以生成类似于 {Clients: [{Hostname: Value, IP: Value, MacAddr: Value}]} 的内容。
目前我的程序能够逐行读取每个字符串并将其存储到一个数组中(该数组初始化错误只是为了测试目的,我将对其进行更改):
int get_list_of_connected_clients(json_object *input, json_object *output) {
FILE *fp;
char path[1035];
int i = 0;
char a[2][100];
fp = popen("./Sample_Bash_Script_Test.sh", "r");
if (fp == NULL) {
printf("Failed To Run Script \n");
exit(1);
}
while (fgets(path, sizeof(path) - 1, fp) != NULL) {
stpcpy(a[i], path);
i++;
}
pclose(fp);
}
有没有人可以帮助我并引导我朝着正确的方向前进? C 中的字符串操作对我来说相对较新,我仍在努力了解它!
编辑:
我的函数现在看起来像这样:
int get_list_of_connected_clients(json_object* input, json_object* output){
FILE *filepath;
char output_line[1035];
int index=0;
char arr_clients[30][100];
filepath = popen("./Sample_Bash_Script_Test.sh", "r");
if (filepath == NULL){
printf("Failed To Run Script \n");
exit(1);
}
while (fgets(output_line, sizeof(output_line)-1, filepath) != NULL){
stpcpy(arr_clients[index], output_line);
index++;
}
pclose(filepath);
/*Creating a json object*/
json_object * jobj = json_object_new_object();
/*Creating a json array*/
json_object *jarray = json_object_new_array();
json_object *jstring1[2][2];
for (int y=0; y < 2; y++) {
int x = 0;
char *p = strtok(arr_clients[y], " ");
char *array[2][3];
while (p != NULL) {
array[y][x++] = p;
p = strtok(NULL, " ");
}
for (x = 0; x < 3; ++x) {
jstring1[y][x] = json_object_new_string(array[y][x]);
/*Adding the above created json strings to the array*/
json_object_array_add(jarray,jstring1[y][x]);
}
}
/*Form the json object*/
json_object_object_add(jobj,"Clients", jarray);
/*Now printing the json object*/
printf ("%s",json_object_to_json_string(jobj));
return 0;
}
我运行它时的输出是这样的:{ "Clients": [ "Hostname", "192.168.1.18", "XX:XX:XX:XX", "Hostname", "192.168.1.13", "XX:XX:XX:XX" ] }
有没有人知道我做错了什么来阻止它在每个客户之后打破列表?即
{
"Clients" : [
{
"Hostname" : "example.com",
"IP" : "127.0.0.1",
"MacAddr" : "mactonight"
},
{
"Hostname" : "foo.biz",
"IP" : "0.0.0.0",
"MacAddr" : "12:34:56:78"
}
]
}
【问题讨论】:
-
对于 JSON,请查看 json-glib 等库。
-
C 对于这种翻译来说有点矫枉过正。您可以改用 Python 等其他语言将 bash 输出转换为 JSON 吗?
-
是的,你是对的,我认为 C 对此有点粗糙,但这是在存储空间不大的嵌入式设备上进行的。所以比起 Python,我可以尝试 Lua。我认为这可能是轻量级和简单的。
-
使用 snprintf 你应该可以做到。 @Schwern 我不认为这是矫枉过正。它是迄今为止最简单的编程语言 (IMO),因此尝试用它做任何他想做的事情都是合法的。
-
@CacahueteFrito 简单并不意味着简单。
标签: c arrays json string json-c