]> xenbits.xensource.com Git - libvirt.git/commitdiff
util: json: add helper to iterate JSON object key=value pairs
authorPeter Krempa <pkrempa@redhat.com>
Tue, 13 Jan 2015 15:43:30 +0000 (16:43 +0100)
committerPeter Krempa <pkrempa@redhat.com>
Sat, 31 Jan 2015 07:53:21 +0000 (08:53 +0100)
This helper eases iterating all key=value pairs stored in a JSON
object. Usually we pick only certain known keys from a JSON object, but
this will allow to walk complete objects and have the callback act on
those.

src/libvirt_private.syms
src/util/virjson.c
src/util/virjson.h

index 499da505dd9ad3f0310890f90873b4b5341a52fa..f7f8ea25c956ffdd522cddaa497f80b6c73a30ee 100644 (file)
@@ -1550,6 +1550,7 @@ virJSONValueObjectAppendNumberUlong;
 virJSONValueObjectAppendString;
 virJSONValueObjectCreate;
 virJSONValueObjectCreateVArgs;
+virJSONValueObjectForeachKeyValue;
 virJSONValueObjectGet;
 virJSONValueObjectGetBoolean;
 virJSONValueObjectGetKey;
index 1bb2653581f90f8343590550c3a28e007d1ad001..c8d761ff2e16e678f888bdac83ee09ee6e2c8384 100644 (file)
@@ -1200,6 +1200,39 @@ virJSONValueObjectIsNull(virJSONValuePtr object,
 }
 
 
+/**
+ * virJSONValueObjectForeachKeyValue:
+ * @object: JSON object to iterate
+ * @cb: callback to call on key-value pairs contained in the object
+ * @opaque: generic data for the callback
+ *
+ * Iterates all key=value pairs in @object. Iteration breaks if @cb returns
+ * negative value.
+ *
+ * Returns 0 if all elements were iterated, -2 if @cb returned negative value
+ * during iteration and -1 on generic errors.
+ */
+int
+virJSONValueObjectForeachKeyValue(virJSONValuePtr object,
+                                  virJSONValueObjectIteratorFunc cb,
+                                  void *opaque)
+{
+    size_t i;
+
+    if (object->type != VIR_JSON_TYPE_OBJECT)
+        return -1;
+
+    for (i = 0; i < object->data.object.npairs; i++) {
+        virJSONObjectPairPtr elem = object->data.object.pairs + i;
+
+        if (cb(elem->key, elem->value, opaque) < 0)
+            return -2;
+    }
+
+    return 0;
+}
+
+
 #if WITH_YAJL
 static int
 virJSONParserInsertValue(virJSONParserPtr parser,
index 57010b010670494aae2863de1afbe27a1f9cd6ec..9bb74613230b9b61e85b1502e1258a5db38b4fc6 100644 (file)
@@ -157,4 +157,12 @@ virJSONValuePtr virJSONValueFromString(const char *jsonstring);
 char *virJSONValueToString(virJSONValuePtr object,
                            bool pretty);
 
+typedef int (*virJSONValueObjectIteratorFunc)(const char *key,
+                                              const virJSONValue *value,
+                                              void *opaque);
+
+int virJSONValueObjectForeachKeyValue(virJSONValuePtr object,
+                                      virJSONValueObjectIteratorFunc cb,
+                                      void *opaque);
+
 #endif /* __VIR_JSON_H_ */