[libvirt] [PATCH v2 2/9] util: add functions for interating over json object

Dmitry Guryanov dguryanov at parallels.com
Wed Apr 18 18:07:36 UTC 2012


Add function virJSONValueObjectKeysNumber, virJSONValueObjectGetKey
and virJSONValueObjectGetValue, which allow you to iterate over all
fields of json object: you can get number of fields and then get
name and value, stored in field with that name by index.

Signed-off-by: Dmitry Guryanov <dguryanov at parallels.com>
---
 src/util/json.c |   30 ++++++++++++++++++++++++++++++
 src/util/json.h |    4 ++++
 2 files changed, 34 insertions(+), 0 deletions(-)

diff --git a/src/util/json.c b/src/util/json.c
index 3258c3f..e7dc272 100644
--- a/src/util/json.c
+++ b/src/util/json.c
@@ -431,6 +431,36 @@ virJSONValuePtr virJSONValueObjectGet(virJSONValuePtr object, const char *key)
     return NULL;
 }
 
+int virJSONValueObjectKeysNumber(virJSONValuePtr object)
+{
+    if (object->type != VIR_JSON_TYPE_OBJECT)
+        return -1;
+
+    return object->data.object.npairs;
+}
+
+const char *virJSONValueObjectGetKey(virJSONValuePtr object, unsigned int n)
+{
+    if (object->type != VIR_JSON_TYPE_OBJECT)
+        return NULL;
+
+    if (n >= object->data.object.npairs)
+        return NULL;
+
+    return object->data.object.pairs[n].key;
+}
+
+virJSONValuePtr virJSONValueObjectGetValue(virJSONValuePtr object, unsigned int n)
+{
+    if (object->type != VIR_JSON_TYPE_OBJECT)
+        return NULL;
+
+    if (n >= object->data.object.npairs)
+        return NULL;
+
+    return object->data.object.pairs[n].value;
+}
+
 int virJSONValueArraySize(virJSONValuePtr array)
 {
     if (array->type != VIR_JSON_TYPE_ARRAY)
diff --git a/src/util/json.h b/src/util/json.h
index 686a8fb..436405f 100644
--- a/src/util/json.h
+++ b/src/util/json.h
@@ -100,6 +100,10 @@ virJSONValuePtr virJSONValueObjectGet(virJSONValuePtr object, const char *key);
 int virJSONValueArraySize(virJSONValuePtr object);
 virJSONValuePtr virJSONValueArrayGet(virJSONValuePtr object, unsigned int element);
 
+int virJSONValueObjectKeysNumber(virJSONValuePtr object);
+const char *virJSONValueObjectGetKey(virJSONValuePtr object, unsigned int n);
+virJSONValuePtr virJSONValueObjectGetValue(virJSONValuePtr object, unsigned int n);
+
 const char *virJSONValueGetString(virJSONValuePtr object);
 int virJSONValueGetNumberInt(virJSONValuePtr object, int *value);
 int virJSONValueGetNumberUint(virJSONValuePtr object, unsigned int *value);
-- 
1.7.1




More information about the libvir-list mailing list