]> git.puffer.fish Git - matthieu/frr.git/commitdiff
lib: convert termtable to json
authorEric Kinzie <ekinzie@labn.net>
Fri, 2 Sep 2022 14:33:21 +0000 (16:33 +0200)
committerLouis Scalbert <louis.scalbert@6wind.com>
Tue, 18 Apr 2023 09:33:15 +0000 (11:33 +0200)
Add a function that returns a JSON-C structure containing a representation
of a termtable.  This is intended to be a quick way to implement JSON
output to CLI commands.

Signed-off-by: Eric Kinzie <ekinzie@labn.net>
lib/termtable.c
lib/termtable.h

index 30f1ab74c6dd755ac08c15b9f195eca7d3879f35..9b36d5ebfa8b04ce224f1b59cbae78f456f2651e 100644 (file)
@@ -7,6 +7,7 @@
 #include <zebra.h>
 #include <stdio.h>
 
+#include "lib/json.h"
 #include "printfrr.h"
 #include "memory.h"
 #include "termtable.h"
@@ -485,3 +486,45 @@ char *ttable_dump(struct ttable *tt, const char *newline)
 
        return buf;
 }
+
+/* Crude conversion from ttable to json array.
+ * Assume that the first row has column headings.
+ *
+ * Formats are:
+ *   d int32
+ *   f double
+ *   l int64
+ *   s string (default)
+ */
+json_object *ttable_json(struct ttable *tt, const char *const formats)
+{
+       struct ttable_cell *row; /* iteration pointers */
+       json_object *json = NULL;
+
+       json = json_object_new_array();
+
+       for (int i = 1; i < tt->nrows; i++) {
+               json_object *jobj;
+               json_object *val;
+
+               row = tt->table[i];
+               jobj = json_object_new_object();
+               json_object_array_add(json, jobj);
+               for (int j = 0; j < tt->ncols; j++) {
+                       switch (formats[j]) {
+                       case 'd':
+                       case 'l':
+                               val = json_object_new_int64(atol(row[j].text));
+                               break;
+                       case 'f':
+                               val = json_object_new_double(atof(row[j].text));
+                               break;
+                       default:
+                               val = json_object_new_string(row[j].text);
+                       }
+                       json_object_object_add(jobj, tt->table[0][j].text, val);
+               }
+       }
+
+       return json;
+}
index 3aa8caee89bd726888b09a735957c95a30818832..7258682bd80a680f047095ace134434443b62d56 100644 (file)
@@ -8,6 +8,7 @@
 #define _TERMTABLE_H_
 
 #include <zebra.h>
+#include "lib/json.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -277,6 +278,17 @@ void ttable_rowseps(struct ttable *tt, unsigned int row,
  */
 char *ttable_dump(struct ttable *tt, const char *newline);
 
+/**
+ * Convert a table to a JSON array of objects.
+ *
+ * Caller must free the returned json_object structure.
+ *
+ * @param tt the table to convert
+ * @param formats an array of characters indicating what JSON type should be
+ * used.
+ */
+json_object *ttable_json(struct ttable *tt, const char *const formats);
+
 #ifdef __cplusplus
 }
 #endif