cURL / Mailing Lists / curl-library / Single Mail

curl-library

Re: Send Remote Source in JSON body

From: Aaron Meriwether <me_at_ameriwether.com>
Date: Tue, 28 Jul 2015 15:13:21 -0600

> On Jul 28, 2015, at 2:55 PM, Robert Hudspeth <hudspeth_at_bigml.com> wrote:
>
> Do you still know if I can modify the JSON body using libcURL?

libcurl does not provide methods for manipulating JSON. You will need to compose your JSON document via some other mechanism, then pass the finished document to libcurl.
The simplest way to compose a JSON document in C is probably to use sprintf to interpolate your data into a JSON skeleton. For example:

char json[1024];
snprintf(buffer, sizeof(json), "{\"foo\":\"%s\",\"bar\":\"%s\"}", fooval, barval);

You will want to make sure the values you provide are properly escaped so that things like double-quotes won't break your JSON skeleton.
Something like this should be sufficient:

static size_t jsonEscape(char *out, char *in) {
  int i, j = 0;
  for(i = 0; in[i] != 0; i++) {
    switch(in[i]) {
      case '"':
        if(out) sprintf(out+j, "\\\""); j += 2; break;
      case '\\':
        if(out) sprintf(out+j, "\\\\"); j += 2; break;
      case 0x08:
        if(out) sprintf(out+j, "\\b"); j += 2; break;
      case 0x09:
        if(out) sprintf(out+j, "\\t"); j += 2; break;
      case 0x0A:
        if(out) sprintf(out+j, "\\n"); j += 2; break;
      case 0x0C:
        if(out) sprintf(out+j, "\\f"); j += 2; break;
      case 0x0D:
        if(out) sprintf(out+j, "\\r"); j += 2; break;
      default:
        if(out) out[j] = in[i]; j++;
    }
  }
  if(out) out[j] = 0;
  return j;
}

There are also plenty of more complex JSON libraries available, to which you can find links on the json.org page.
-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2015-07-28