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.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, json_key_data(key0),
  23. (val0 == NULL));
  24. if (strcmp(json_key_data(key0), "deleteme") == 0)
  25. {
  26. json_object_object_del(my_object, json_key_data(key0));
  27. printf(" (deleted)\n");
  28. }
  29. else
  30. printf(" (kept)\n");
  31. orig_count++;
  32. }
  33. printf("==== replace-value first loop starting ====\n");
  34. const struct json_key *original_key = NULL;
  35. orig_count = 0;
  36. json_object_object_foreach(my_object, key, val)
  37. {
  38. printf("Key at index %d is [%s] %d\n", orig_count, json_key_data(key),
  39. (val == NULL));
  40. orig_count++;
  41. if (strcmp(json_key_data(key), "foo2") != 0)
  42. continue;
  43. printf("replacing value for key [%s]\n", json_key_data(key));
  44. original_key = key;
  45. json_object_object_add(my_object, json_key_data(key0),
  46. json_object_new_string("zzz"));
  47. }
  48. printf("==== second loop starting ====\n");
  49. int new_count = 0;
  50. int retval = 0;
  51. json_object_object_foreach(my_object, key2, val2)
  52. {
  53. printf("Key at index %d is [%s] %d\n", new_count, json_key_data(key2),
  54. (val2 == NULL));
  55. new_count++;
  56. if (strcmp(json_key_data(key2), "foo2") != 0)
  57. continue;
  58. printf("pointer for key [%s] does %smatch\n", json_key_data(key2),
  59. (key2 == original_key) ? "" : "NOT ");
  60. if (key2 != original_key)
  61. retval = 1;
  62. }
  63. if (new_count != orig_count)
  64. {
  65. printf("mismatch between original count (%d) and new count (%d)\n", orig_count,
  66. new_count);
  67. retval = 1;
  68. }
  69. json_object_put(my_object);
  70. return retval;
  71. }