如何拆分多行字符串并将其存储到C语言的json数组中

时间:2019-04-12 17:41:14

标签: c arrays json string json-c

我有一个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"
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

使用json-glib之类的库为您构建JSON,而不是尝试以字符串形式构建JSON。这更加灵活,可以处理各种边缘情况。它提供JsonBuilder来构建JSON结构。

我们从获取文件指针开始,应该用其他方法打开文件。然后,我们启动JsonBuilder并开始构建声明{ "Clients"对象的JSON结构并启动数组。

JsonNode *bash_connected_clients_to_json(FILE *fp) {
    JsonBuilder *builder = json_builder_new();

    // { "Clients": [ ...
    json_builder_begin_object(builder);
    json_builder_set_member_name(builder, "Clients");
    json_builder_begin_array(builder);

现在,我们阅读每一行,并将其和构建器发送到一个函数中,以处理该行并将其添加到打开的数组中。

    char line[1024];
    while (fgets(line, sizeof(line), fp) != NULL) {
        bash_connected_clients_line_to_json(line, builder);
    }

最后关闭数组和对象,并返回我们刚刚构建的JsonNode

    // ... ] }
    json_builder_end_array(builder);
    json_builder_end_object(builder);

    return json_builder_get_root(builder);
}

然后可以打印JsonNode。

int main() {
    JsonNode *json = bash_connected_clients_to_json(stdin);
    printf("%s", json_to_string(json, TRUE));
}

处理每一行都是从解析开始。这可以在各种方式下完成。 sscanf工作正常。

void bash_connected_clients_line_to_json( const char *line, JsonBuilder *builder ) {    
    char hostname[1024], ip[1024], macaddr[1024];
    if( sscanf(line, "%1023s %1023s %1023s", hostname, ip, macaddr) != 3 ) {
        fprintf(stderr, "Could not parse line: '%s'\n", line);
        return;
    }

然后,将JSON对象添加到已经打开的数组中,将每个元素添加到对象中,然后关闭对象。

    // { "Hostname": "foo", "IP", "bar", "MacAddr", "baz" }
    json_builder_begin_object(builder);

    json_builder_set_member_name(builder, "Hostname");
    json_builder_add_string_value(builder, hostname);

    json_builder_set_member_name(builder, "IP");
    json_builder_add_string_value(builder, ip);

    json_builder_set_member_name(builder, "MacAddr");
    json_builder_add_string_value(builder, macaddr);

    json_builder_end_object(builder);
}

$ cat > test.txt
example.com 127.0.0.1 mactonight
foo.biz 0.0.0.0 12:34:56:78

$ ./test < test.txt
{
  "Clients" : [
    {
      "Hostname" : "example.com",
      "IP" : "127.0.0.1",
      "MacAddr" : "mactonight"
    },
    {
      "Hostname" : "foo.biz",
      "IP" : "0.0.0.0",
      "MacAddr" : "12:34:56:78"
    }
  ]
}

或者您可以在几行Ruby中做到这一点。

require 'json'

clients = []

STDIN.each do |line|
  fields = line.split(/\s+/)
  clients << {
    Hostname: fields[0],
    IP: fields[1],
    MacAddr: fields[2]
  }
end

connections = {}
connections[:Clients] = clients
puts connections.to_json

对于json-c基本上是相同的。主要区别在于,它不会bash_connected_clients_line_to_json向构建器添加JSON对象,而是返回JSON对象。

json_object* bash_connected_clients_line_to_json( const char *line ) {    
    char hostname[1024], ip[1024], macaddr[1024];
    if( sscanf(line, "%1023s %1023s %1023s", hostname, ip, macaddr) != 3 ) {
        fprintf(stderr, "Could not parse line: '%s'\n", line);
        return NULL;
    }

    json_object *json = json_object_new_object();

    json_object_object_add(json, "Hostname", json_object_new_string(hostname));
    json_object_object_add(json, "IP", json_object_new_string(ip));
    json_object_object_add(json, "MacAddr", json_object_new_string(macaddr));

    return json;
}

然后将其添加到客户端的JSON数组中。

json_object *bash_connected_clients_to_json(FILE *fp) {
    json_object *clients = json_object_new_array();

    char line[1024];
    while (fgets(line, sizeof(line), fp) != NULL) {
        json_object_array_add(
            clients,
            bash_connected_clients_line_to_json(line)
        );
    }

    json_object *json = json_object_new_object();
    json_object_object_add(json, "Clients", clients);

    return json;
}