Search code examples
cescapingjson-c

json-c string with "/" character


When my program saves something in json like this:

 json_object_object_add(jObj_my, "cats/dogs", json_object_new_double(cats/dogs));

the result in the .json file is:

"cats\/dogs" : some_double_number

How can i avoid it to print "\/" instead of "/"?


Solution

  • The json-c library's code in its GitHub repository has a flag to make escaping of / optional.

    If you do not want the generated string to escape this, use the JSON_C_TO_STRING_NOSLASHESCAPE flag, like this:

    #include <stdio.h>
    #include <json.h>
    
    int main(int argc, char **argv)
    {
        json_object *my_string;
    
        my_string = json_object_new_string("/foo/bar/baz");
        printf("my_string=%s\n", json_object_get_string(my_string));
        printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
        printf("my_string.to_string(NOSLASHESCAPE)=%s\n", json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE));
        json_object_put(my_string);
    
        return 0;
    }
    

    example adapted from https://github.com/json-c/json-c/blob/master/tests/test1.c#L155

    Saving this in slashtest.c, compiling it, and running it produces:

    $ gcc -Wall slashtest.c -L/usr/local/lib -l:libjson-c.a -I/usr/local/include/json-c
    $ ./a.out
    my_string=/foo/bar/baz
    my_string.to_string()="\/foo\/bar\/baz"
    my_string.to_string(NOSLASHESCAPE)="/foo/bar/baz"
    

    Escaping / in JSON is legal and arguably may be useful, see this post about it: JSON: why are forward slashes escaped?

    Note that this flag was added to the library's code in 2015, but that, somehow the change didn't make it in the latest current json-c-0.12.1 release made in Jun 7, 2016. I am unsure why.

    So to use it, you will have to get the code from GitHub, and compile it.