c – 为什么Jansson的is_json_object()无法识别我的JSON字符串?
我是C新手,无法弄清楚如何从字符串中删除一些杂项数据,然后将其解析为
JSON.
我最终使用了我能找到的记录最多的JSON解析器 – jansson.看起来很棒,虽然我陷入了第一道障碍. 我的程序收到以下格式的字符串: 5::/chat:{"name":"steve","args":[{"connection":"true"},{ "chatbody" : "I am the body" }]} 我已经删除了大括号外的所有内容: std::string str=message; unsigned pos = str.find("{"); std::string string = str.substr (pos); 离开: { "name": "steve","args": [ { "connection": "true" },{ "chatbody": "I am the body" } ] } 我陷入第一阶段解析这个问题.我已经将字符串转换为char,然后尝试使用json_loads,但是我没有得到任何有用的东西…… 整件事看起来像这样: void processJson(string message) { json_t *root; json_error_t error; size_t i; std::string str=message; unsigned pos = str.find("{"); std::string str3 = str.substr (pos); const char * c = str.c_str(); json_t *data,*sha,*name; root = json_loads(c,&error); data = json_array_get(root,i); cout << data; if(!json_is_object(root)) { fprintf(stderr,"error: commit data %d is not an objectn",i + 1); } } 我需要得到价值,但我只是得到01,02,03 …… is_json_object只是说: error: commit data 1068826 is not an object error: commit data 1068825 is not an object error: commit data 1068822 is not an object 我做错了什么,如何正确格式化?最终我需要迭代一个数组,但无法通过它.我确定这只是初学者的错误. -编辑- 由于严格的尺寸要求,试图避免使用Boost. 解决方法
您可以始终使用现有的解决方案,如Boost的属性树,该属性树具有自动解析JSON文件的功能.它实际上就像添加这两个标题一样简单:
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> 然后添加这一小段代码,其中jsonfile显然意味着你的文件名. boost::property_tree::ptree jsontree; boost::property_tree::read_json(jsonfile,jsontree); 如果您想从JSON树中提取信息,可以这样做,其中type是您要提取的数据的类型,insert.key.path.here是您的密钥的路径,每个父级按句点分隔的键. jsonfile.get<type>(insert.key.path.here); 另外,我不相信你在那里的JSON字符串是有效的.你做了很好的删除JSON字符串本身周围的多余,但我相信这里有一个问题: "connection" : true, 您可以在此处检查JSON字符串的有效性:http://jsonformatter.curiousconcept.com/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |