-->
Page 1 of 1

Sample NONOS JSON code anyone?

PostPosted: Sat Apr 09, 2016 8:55 am
by papadeltasierra
Anyone got some example JSON parsing code that they would be willing to share? Something using the NONOS jsonparse_setup() etc library please.

Re: Sample NONOS JSON code anyone?

PostPosted: Sun Apr 10, 2016 10:13 am
by papadeltasierra
OK, didn't find any so here is some code below that will help you understand how to use it. But first...
** Beware **
The NONOS SDK version of this code does not cope with certain bits of JSON such as empty objects '{}' or floating point values. The current Contiki source code has a newer and better implementation providing you are willing to extract known floating point values as strings and do the conversion yourself.
Code: Select all#include <stdio.h>
#include "jsonparse.h"

int main(int argc, char *argv[])
{
  char string[128];
  int json_type;
  struct jsonparse_state state;
  int units;
  int tenths;

  jsonparse_setup(&state, data, strlen(data));

  while(json_type = jsonparse_next(&state))
  {
    switch (json_type)
    {
      case JSON_TYPE_ARRAY:
        printf("Array:\n");
        break;

      case JSON_TYPE_OBJECT:
        printf("Object:\n");
        break;

      case JSON_TYPE_PAIR:
        printf("Pair:\n");
        break;

      case JSON_TYPE_PAIR_NAME:
        printf("Pair name: ");
        jsonparse_copy_value(&state, string, 128);
        printf("%s\n", string);
        break;

      case JSON_TYPE_STRING:
        printf("String: ");
        jsonparse_copy_value(&state, string, 128);
        printf("%s\n", string);
        break;

      case JSON_TYPE_INT:
        printf("Int: ");
        printf("%d\n", jsonparse_get_value_as_int(&state));
        break;

      case JSON_TYPE_NUMBER:
        printf("Number: ");
        printf("%ld\n", jsonparse_get_value_as_long(&state));
        break;

      case JSON_TYPE_ERROR:
        printf("Error:\n");
        break;

      default:
        // Turns out these are the ASCII codes for non-whitespace in the JSON
        // that is not handled as special case by the parser.
        printf("Unknown type: %d\n", json_type);
        break;
    }
  }
  return(0);
}