提交 a6f277a6 编写于 作者: P Peter Krempa

util: json: add helper to iterate JSON object key=value pairs

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.
上级 58f61d24
......@@ -1550,6 +1550,7 @@ virJSONValueObjectAppendNumberUlong;
virJSONValueObjectAppendString;
virJSONValueObjectCreate;
virJSONValueObjectCreateVArgs;
virJSONValueObjectForeachKeyValue;
virJSONValueObjectGet;
virJSONValueObjectGetBoolean;
virJSONValueObjectGetKey;
......
......@@ -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,
......
......@@ -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_ */
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册