diff options
author | Eric Haszlakiewicz <erh+git@nimenees.com> | 2012-07-24 23:27:41 -0500 |
---|---|---|
committer | Eric Haszlakiewicz <erh+git@nimenees.com> | 2012-07-24 23:27:41 -0500 |
commit | 6988f53fcb05c13d99dd846494d79ea3bb3b1d4c (patch) | |
tree | 204aece682b23563bb42a7f5d2889b19d71e9c0c /json_object.c | |
parent | 381f77c5bccf20234a2bddae2b6ac43997faf0a2 (diff) |
Rewrite json_object_object_add to replace just the value if the key already exists so keys remain valid.
This is particularly useful when replacing values in a loop, since it allows
the key used by json_object_object_foreach to continue to be used.
Diffstat (limited to 'json_object.c')
-rw-r--r-- | json_object.c | 16 |
1 files changed, 14 insertions, 2 deletions
diff --git a/json_object.c b/json_object.c index 2258c02..8dd13b0 100644 --- a/json_object.c +++ b/json_object.c @@ -306,8 +306,20 @@ struct lh_table* json_object_get_object(struct json_object *jso) void json_object_object_add(struct json_object* jso, const char *key, struct json_object *val) { - lh_table_delete(jso->o.c_object, key); - lh_table_insert(jso->o.c_object, strdup(key), val); + // We lookup the entry and replace the value, rather than just deleting + // and re-adding it, so the existing key remains valid. + json_object *existing_value = NULL; + struct lh_entry *existing_entry; + existing_entry = lh_table_lookup_entry(jso->o.c_object, (void*)key); + if (!existing_entry) + { + lh_table_insert(jso->o.c_object, strdup(key), val); + return; + } + existing_value = (void *)existing_entry->v; + if (existing_value) + json_object_put(existing_value); + existing_entry->v = val; } struct json_object* json_object_object_get(struct json_object* jso, const char *key) |