0

I need to just create strings in JSON format in C that will be manipulated by a Node.js script. The C program doesn't need to use or manipulate a JSON object.

The problem is that I have strings that could contain double-quotes and other characters that could break the JSON string. So I need a simple way to escape strings accordingly to the JSON standard, as lightweight as possible.

I will appreciate any sugestions to solve this problem. Thanks in advance!

Paulo Alexandre
  • 600
  • 1
  • 8
  • 17
  • Thanks for your comment, but I don't pretend to use files for that. The strings will be generated by the C program at runtime. Any other suggestions? – Paulo Alexandre Aug 25 '15 at 14:29
  • Sorry I misread it . If you have only strings then just use `sscanf` to get the part which you need from the generated string . – ameyCU Aug 25 '15 at 14:31
  • 1
    Go over every character in the string and add a backslash before every backslash and before every quote. Make sure you do this exactly once. Related: [How should I escape strings in JSON?](http://stackoverflow.com/a/3020108/249237) – Kninnug Aug 25 '15 at 14:34
  • Thanks again @ameyCU! But I can't see how `sscanf` could help me. Note that the C program doesn't need to understand the JSON structure. – Paulo Alexandre Aug 25 '15 at 14:46

3 Answers3

1

Loop through your input string one character at a time and add in backslashes where necessary:

void escape(char *in, char *out) {
    while (*in) {
        switch (*in) {
        case '\\':
        case '"':
            *(out++) = '\\';
            *(out++) = *in;
            break;
        case '\n':
            *(out++) = '\\';
            *(out++) = 'n';
            break;
        ...
        default:
            *(out++) = *in;
            break;
        }
        in++;
    }
}
nemetroid
  • 2,027
  • 13
  • 20
0

If you are ok with using glib, the g_strescape routine might work: 'https://developer.gnome.org/glib/stable/glib-String-Utility-Functions.html#g-strescape'

Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\v', '\' and '"' in the string source by inserting a '\' before them. Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a '\' followed by their octal representation. Characters supplied in exceptions are not escaped.

Rob Latham
  • 4,734
  • 2
  • 21
  • 42
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * escape_string_for_json(char *str) {

    // allocate the length of str
    char *nstr = calloc(strlen(str) + 1, sizeof(char));

    // loop through each character
    long unsigned int c = 0;
    long unsigned int d = 0;
    while (c < strlen(str)) {
        printf("character: %c\n", str[c]);

        // json needs everything from '\x00' to '\x1f' escaped
        if (str[c] == '"' || str[c] == '\\' || ('\x00' <= str[c] && str[c] <= '\x1f')) {
            printf("\tescaping %c\n", str[c]);

            // add the escape character to nstr
            nstr[d] = '\\';

            // increment d to account for the extra space
            d++;

            // allocate that space in the nstr pointer
            nstr = realloc(nstr, d);

            // add the character
            nstr[d] = str[c];

        } else {
            // add the character to nstr
            nstr[d] = str[c];
        }

        c++;
        d++;

    }

    // add the \0 at the end
    nstr[d] = '\0';

    return nstr;

}

int main( int argc, char *argv[] )  {

    printf("string to escape: \"%s\"\n", argv[1]);

    char *str;
    str = escape_string_for_json(argv[1]);

    printf("escaped string: \"%s\"\n", str);

    free(str);

}
gcc pgrm.c
./a.out "string to \" escape"
  • Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants. – Jaimil Patel May 25 '20 at 19:23
  • It is escaping characters that need it in json strings which is the title and to understand it further there are comments in the code. – Andrew Hodel May 26 '20 at 20:33