json-c string with “/” character

十年热恋 提交于 2020-08-07 18:01:05

问题


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 "/"?


回答1:


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.



来源:https://stackoverflow.com/questions/44588310/json-c-string-with-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!