You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

testReplaceExisting.c 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <stddef.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "json.h"
  6. int main(int argc, char **argv)
  7. {
  8. MC_SET_DEBUG(1);
  9. /*
  10. * Check that replacing an existing object keeps the key valid,
  11. * and that it keeps the order the same.
  12. */
  13. json_object *my_object = json_object_new_object();
  14. json_object_object_add(my_object, "foo1", json_object_new_string("bar1"));
  15. json_object_object_add(my_object, "foo2", json_object_new_string("bar2"));
  16. json_object_object_add(my_object, "deleteme", json_object_new_string("bar2"));
  17. json_object_object_add(my_object, "foo3", json_object_new_string("bar3"));
  18. printf("==== delete-in-loop test starting ====\n");
  19. int orig_count = 0;
  20. json_object_object_foreach(my_object, key0, val0)
  21. {
  22. printf("Key at index %d is [%s] %d", orig_count, key0, (val0 == NULL));
  23. if (strcmp(key0, "deleteme") == 0)
  24. {
  25. json_object_object_del(my_object, key0);
  26. printf(" (deleted)\n");
  27. }
  28. else
  29. printf(" (kept)\n");
  30. orig_count++;
  31. }
  32. printf("==== replace-value first loop starting ====\n");
  33. const struct json_key *original_key = NULL;
  34. orig_count = 0;
  35. json_object_object_foreach_len(my_object, key, val)
  36. {
  37. printf("Key at index %d is [%s] %d\n", orig_count, json_key_data(key),
  38. (val == NULL));
  39. orig_count++;
  40. if (strcmp(json_key_data(key), "foo2") != 0)
  41. continue;
  42. printf("replacing value for key [%s]\n", json_key_data(key));
  43. original_key = key;
  44. json_object_object_add(my_object, json_key_data(key),
  45. json_object_new_string("zzz"));
  46. }
  47. printf("==== second loop starting ====\n");
  48. int new_count = 0;
  49. int retval = 0;
  50. json_object_object_foreach_len(my_object, key2, val2)
  51. {
  52. printf("Key at index %d is [%s] %d\n", new_count, json_key_data(key2),
  53. (val2 == NULL));
  54. new_count++;
  55. if (strcmp(json_key_data(key2), "foo2") != 0)
  56. continue;
  57. printf("pointer for key [%s] does %smatch\n", json_key_data(key2),
  58. (key2 == original_key) ? "" : "NOT ");
  59. if (key2 != original_key)
  60. retval = 1;
  61. }
  62. if (new_count != orig_count)
  63. {
  64. printf("mismatch between original count (%d) and new count (%d)\n", orig_count,
  65. new_count);
  66. retval = 1;
  67. }
  68. json_object_put(my_object);
  69. return retval;
  70. }