Search code examples
cjsonstringprintfansi-c

Putting Curly braces in a string in C


I am using a JSON parser with C. The JSON request requires curly braces. I am trying to insert user input into one of the JSON request fields. To do this, I have a variable that stores the first half of the request, a variable for the user input, and a variable for the rest of the JSON request. I use snprintf to combine the variables together. I can't seem to get the last curly brace to go through.

const char *open_brace = "}}";
    char buf[306];  
    char trackingnum[18];

    char *test = "{\"UPSSecurity\": {\"UsernameToken\": {\"Username\": \"[email protected]\",\"Password\": \"xxxxxxxxxxxxxxxx\"},\"ServiceAccessToken\": {\"AccessLicenseNumber\": \"8D421B74FBC948C8\"}},\"TrackRequest\": {\"Request\": {\"RequestOption\": \"1\",\"TransactionReference\": {\"CustomerContext\": \"\"}},\"InquiryNumber\": \"";
    char ending[10] = "\"}}";
    strcat (ending, open_brace);

    printf("\nEnter a tracking number: ");
    scanf(" %s",trackingnum);
    printf("\nTracking num is: %s\n",trackingnum);

     snprintf(buf, sizeof(buf), "%s%s%s%s", test, trackingnum, ending, open_brace );

    printf("\nBuf is: %s\n\n\n\n",buf);
    char *postthis = buf;

Output:

Enter a tracking number: 1ZY5841YYW90351446

Tracking num is: 1ZY5841YYW90351446

Buf is: {"UPSSecurity": {"UsernameToken": {"Username": "[email protected]","Password": "xxxxxxxxxxxxxxxx"},"ServiceAccessToken": {"AccessLicenseNumber": "8D421B74FBC948C8"}},"TrackRequest": {"Request": {"RequestOption": "1","TransactionReference": {"CustomerContext": ""}},"InquiryNumber": "1ZY5841YYW90351446"}




{"Error":{"Code":"4","Description":"JSON Syntax error"}}
jobj from str:
---
{
   "Error": {
     "Code": "4",
     "Description": "JSON Syntax error"
   }
 }

Solution

  • You've sized buf incorrectly. Since you're using snprintf, it's truncating the text you're putting in so that it fits in the available space.

    A better way to do what you're trying to do is to use malloc as then you can specify the correct size for buf like this:

    char *buf = malloc(strlen(test) + strlen(trackingnum) + strlen(ending) + strlen(open_brace)+1);
    sprintf(buf, "%s%s%s%s", test, trackingnum, ending, open_brace );
    

    You can then also use sprintf as you know that the combined length of the strings plus the extra space for the NUL character will fit.

    And once you've done with buf, don't forget to free it.

    You should also make sure that the amount entered into trackingnum isn't more than it's able to hold too.