c语言中的jsonpath的处理
一、背景
? ? 由于項目中需要使用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
目前還不支持*的運算。
?
總結
以上是生活随笔為你收集整理的c语言中的jsonpath的处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序之坦克大战学习
- 下一篇: 使用PHP得到所有的HTTP请求头