Example #1
0
// creates new packet from key:object
packet_t packet_get_packet(packet_t p, char *key)
{
  packet_t pp;
  int val;
  if(!p || !key) return NULL;

  val = j0g_val(key,(char*)p->json,p->js);
  if(!val) return NULL;

  pp = packet_new();
  packet_json(pp, p->json+p->js[val], p->js[val+1]);
  return pp;
}
Example #2
0
// TODO allow empty val to remove existing
void packet_set(packet_t p, char *key, char *val, int vlen)
{
  unsigned char *json, *at, *eval;
  int existing, klen, len, evlen;

  if(!p || !key || !val) return;
  if(p->json_len < 2) packet_json(p, (unsigned char*)"{}", 2);
  klen = strlen(key);
  if(!vlen) vlen = strlen(val); // convenience

  // make space and copy
  if(!(json = malloc(klen+vlen+p->json_len+4))) return;
  memcpy(json,p->json,p->json_len);

  // if it's already set, replace the value
  existing = j0g_val(key,(char*)p->json,p->js);
  if(existing)
  {
    // looks ugly, but is just adjusting the space avail for the value to the new size
    eval = json+p->js[existing];
    evlen = p->js[existing+1];
    // if existing was in quotes, include them
    if(*(eval-1) == '"')
    {
      eval--;
      evlen += 2;
    }
    memmove(eval+vlen,eval+evlen,(json+p->json_len) - (eval+evlen)); // frowney face
    memcpy(eval,val,vlen);
    len = p->json_len - evlen;
    len += vlen;
  }else{
    at = json+(p->json_len-1); // points to the "}"
    // if there's other keys already, add comma
    if(p->js[0])
    {
      *at = ','; at++;
    }
    *at = '"'; at++;
    memcpy(at,key,klen); at+=klen;
    *at = '"'; at++;
    *at = ':'; at++;
    memcpy(at,val,vlen); at+=vlen;
    *at = '}'; at++;
    len = at - json;
  }
  packet_json(p, json, len);
  free(json);
}
Example #3
0
path_t path_parse(char *json, int len)
{
  unsigned short js[64];
  path_t p;
  
  if(!json) return NULL;
  if(!len) len = strlen(json);
  js0n((unsigned char*)json, len, js, 64);
  if(!j0g_val("type",json,js)) return NULL;
  p = path_new(j0g_str("type",json,js));

  // just try to set all possible attributes
  path_ip(p, j0g_str("ip",json,js));
  if(j0g_str("port",json,js)) path_port(p, (uint16_t)strtol(j0g_str("port",json,js),NULL,10));
  path_id(p, j0g_str("id",json,js));
  path_http(p, j0g_str("http",json,js));
  
  return p;
}
Example #4
0
// return the null-terminated string value matching the given key
char *j0g_str(char *key, char *json, unsigned short *index)
{
    int val = j0g_val(key, json, index);
    if(!val) return NULL;
    return j0g_safe(val, json, index);
}