c++ - 为什么 Jansson 的 is_json_object() 无法识别我的 JSON 字符串?

标签 c++ json jansson

我是 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, 0, &error);
    data = json_array_get(root, i);        
    cout << data;

    if(!json_is_object(root))
    {
      fprintf(stderr, "error: commit data %d is not an object\n", 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 文件的功能。就像添加这两个 header 一样简单:

#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 树中提取信息,你可以这样做,其中类型是你想要提取的数据类型,而 insert.key.path.here 是你的 key 的路径,每个父键用句点分隔。

jsonfile.get<type>(insert.key.path.here);

另外,我不相信你那里的 JSON 字符串是有效的。您很好地删除了 JSON 字符串本身周围的多余内容,但我认为这里存在问题:

"connection" : true,

您可以在此处检查 JSON 字符串的有效性:http://jsonformatter.curiousconcept.com/

关于c++ - 为什么 Jansson 的 is_json_object() 无法识别我的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514611/

相关文章:

c++ - 将 'const' 作为 'this' 参数传递时出错

javascript - 将具有特殊值的 JSON 对象作为字符串加载

javascript - 语法错误: Unexpected Token: on AJAX request

与库链接的 C 程序

c++ - 虚函数调用非虚函数,反之亦然

c++ - RTTI 是指动态绑定(bind)吗?

c++ - 使用非 constexpr 函数设置 constexpr 变量(但可以在编译时计算)

javascript - Jquery 的 JSON 递归循环问题

c - 如何将librdkafka负载转换为json以获取参数值?

c++ - C 和 C++ 之间的缓冲区相同方法中的文件读取?