一、背景
由于项目中需要使用jsonpath,所以记录一下jsonpath的使用过程。
二、过程
2.1 在百度中查找不同的c语言的json库,发现没有可用的jsonpath功能模块。
2.2 随后找到了glib中有个json-glib有处理jsonpath的模块,随机,在ubuntu中安装json-glib,刚开始是通过源码来安装的,但是有些问题过不去,就采用了命令apt-get安装,安装命令如下:
apt-get install libjson-glib-1.0-0 libjson-glib-dev
2.3 随后,写了main.c函数来测试相关api函数调用,代码如下:
#include<stdio.h>
#include<json-glib/json-glib.h>
#include "json-glib/json-path.h"
#include "json-glib/json-generator.h"
void main()
{
char *json_data = "{ \"store\": {"
"\"book\": ["
"{ \"category\": \"reference\", \"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\", \"price\": \"8.95\" },"
"{ \"category\": \"fiction\", \"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\", \"price\": \"12.99\" },"
"{ \"category\": \"fiction\", \"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\","
"\"price\": \"8.99\" },"
"{ \"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\","
"\"price\": \"22.99\" }"
"],"
"\"bicycle\": { \"color\": \"red\", \"price\": \"19.95\" }"
"}"
"}";
char *path_str = "$.store.book[0].title";
JsonParser *parser = json_parser_new();
json_parser_load_from_data(parser, json_data, -1, NULL);
//json_parser_load_from_file(parser, "./test_json.txt", NULL);
JsonNode *result;
JsonPath *path = json_path_new();
json_path_compile(path, path_str, NULL);
result = json_path_match(path, json_parser_get_root(parser));
JsonGenerator *generator = json_generator_new();
json_generator_set_root(generator, result);
char *str = json_generator_to_data(generator, NULL);
g_print("Results: %s\n", str);
}
编译的命令如下:
gcc main.c -g -o test_json_glib $(pkg-config --cflags --libs json-glib-1.0)
运行的结果如下:
参考的链接:https://developer.gnome.org/json-glib/stable/JsonPath.html#json-path-match
/
项目中采用的是jansson项目branch(json_path)的实现,具体链接:
https://github.com/akheron/jansson/compare/master...rogerz:json_path
使用的jansson版本是2.11版本,然后将改动加到2.11版本中,修改了相关api的参数的问题就可以使用json_path_get函数来查找path。
修改的地方如下:
然后编译即可。
目前相关wiki中描述,链接:https://github.com/rogerz/jansson/wiki/Json-Path
目前还不支持*的运算。