带有"/"的json-c字符串特点 [英] json-c string with "/" character

查看:438
本文介绍了带有"/"的json-c字符串特点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的程序将这样的内容保存在json中时:

When my program saves something in json like this:

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

.json文件中的结果为:

the result in the .json file is:

"cats\/dogs" : some_double_number

如何避免打印"\/"而不是"/"?

推荐答案

其GitHub存储库中的json-c库代码具有一个标志,使转义/是可选的.

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

如果您不希望生成的字符串对此进行转义,请使用JSON_C_TO_STRING_NOSLASHESCAPE标志,如下所示:

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;
}

示例改编自 https://github .com/json-c/json-c/blob/master/tests/test1.c#L155

将其保存在slashtest.c中,对其进行编译并运行将产生:

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"

在JSON中转义/是合法的并且可以说是有用的,请参阅有关此内容的文章:

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

请注意,此标志已在2015年添加到库的代码中,但是,以某种方式,此更改并未在2016年6月7日发布的最新最新json-c-0.12.1版本中进行.我不确定为什么

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.

因此,要使用它,您将必须从GitHub获取代码并进行编译.

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

这篇关于带有"/"的json-c字符串特点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆