Advertisement
Guest User

Untitled

a guest
Aug 31st, 2015
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "../jsmn.h"
  4.  
  5. /*
  6. * This example shows how many tokes are there in json and how they
  7. * get parsed, we can use this as reference to parse big jsons,
  8. * where we need to track i, i.e. counter for parsing.
  9. */
  10.  
  11. const char *JSON_STRING =
  12. "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
  13. "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
  14.  
  15. static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
  16. if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
  17. strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
  18. return 0;
  19. }
  20. return -1;
  21. }
  22.  
  23. int main() {
  24. int i;
  25. int r;
  26. jsmn_parser p;
  27. jsmntok_t t[128]; /* We expect no more than 128 tokens */
  28.  
  29. jsmn_init(&p);
  30. r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
  31. if (r < 0) {
  32. printf("Failed to parse JSON: %d\n", r);
  33. return 1;
  34. }
  35.  
  36. printf("---------------------------------------------------------\n");
  37. printf("actual json to parse :\n");
  38. printf("%s\n", JSON_STRING);
  39. printf("---------------------------------------------------------\n");
  40. /* A non-negative return value of jsmn_parse is
  41. the number of tokens actually used by the parser. */
  42. printf("here jsmn_parse actually parsed %d tokens\n", r);
  43.  
  44. printf("tokens are as below:\n\n");
  45.  
  46. for (i=0; i < r; i++) {
  47. switch(t[i].type) {
  48. case JSMN_PRIMITIVE:
  49. printf("%d: type : JSMN_PRIMITIVE, child tokens(size): %d ", i, t[i].size); break;
  50. case JSMN_OBJECT:
  51. printf("%d: type : JSMN_OBJECT, child tokens(size): %d ", i, t[i].size ); break;
  52. case JSMN_ARRAY:
  53. printf("%d: type : JSMN_ARRAY, child tokens(size): %d ", i, t[i].size); break;
  54. case JSMN_STRING:
  55. printf("%d: type : JSMN_STRING, child tokens(size): %d ", i, t[i].size); break;
  56. }
  57. printf("token : %s\n\n",strndup(JSON_STRING + t[i].start, t[i].end-t[i].start));
  58. }
  59.  
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement