【问题标题】:Using libparson to parse arrays使用 libparson 解析数组
【发布时间】:2022-01-25 17:37:58
【问题描述】:

我正在编写一个在 Linux 上运行的 C 应用程序,它使用 libparson 来解析 JSON 文件。

https://github.com/mofywong/libparson

我有以下 JSON 文件,该文件被读入我的应用程序中的 char*,名为 reply

{
    "entries": 
    [   {
            "timestampEnd": "2022-02-11T10:19:00.00Z",
            "timestampStart": "2022-02-11T10:00:00.000Z",
            "value": 1001
        },
        {
            "timestampEnd": "2022-02-11T14:47:00.00Z",
            "timestampStart": "2022-02-11T13:19:00.000Z",
            "value": 2000
        }
    ]
}

我正在努力正确解析条目数组。我的代码尝试如下:

JSON_Value*  root_value         = json_parse_string(reply);
JSON_Array*  entries            = json_value_get_array(root_value);

for (int i = 0; i < json_array_get_count(entries); i++)
{
    printf("Inside array parsing loop\n");
    JSON_Object *entry         = json_array_get_object(entries, i);

    const char* timestampStart = json_object_dotget_string(entry, "timestampStart");
    const char* timestampEnd   = json_object_dotget_string(entry, "timestampEnd");
    unsigned int value         = (unsigned int)json_object_dotget_number(entry, "value");
    // process values               
}

执行永远不会进入循环内部。我到底在做什么错?提前致谢。

【问题讨论】:

  • 您是否尝试过打印json_array_get_count(entries) 以查看它是否给出了正确的计数?看起来您正在将作为 JSON 对象的根对象转换为数组。您必须获取根对象的entries 值。
  • @Shahriar 感谢您的回复。我在关注其他示例和 JSON_Array* entries = json_value_get_array(root_value);是如何实施的。我觉得我确实在这里遗漏了一些愚蠢的东西,但我没有发现它

标签: c json parsing jsonparser


【解决方案1】:

正如我所说,您正在将作为 JSON 对象的根对象转换为数组。您必须获取根对象的条目值:

#include <stdio.h>
#include "parson.h"

const char* reply =
    "{\n"
    "    \"entries\": \n"
    "    [   {\n"
    "            \"timestampEnd\": \"2022-02-11T10:19:00.00Z\",\n"
    "            \"timestampStart\": \"2022-02-11T10:00:00.000Z\",\n"
    "            \"value\": 1001\n"
    "        },\n"
    "        {\n"
    "            \"timestampEnd\": \"2022-02-11T14:47:00.00Z\",\n"
    "            \"timestampStart\": \"2022-02-11T13:19:00.000Z\",\n"
    "            \"value\": 2000\n"
    "        }\n"
    "    ]\n"
    "}";

int main()
{
    JSON_Value* root_value = json_parse_string(reply);
    JSON_Array* entries = json_object_dotget_array(json_value_get_object(root_value), "entries");

    for (int i = 0; i < json_array_get_count(entries); i++)
    {
        printf("Inside array parsing loop\n");
        JSON_Object* entry = json_array_get_object(entries, i);

        const char* timestampStart = json_object_dotget_string(entry, "timestampStart");
        const char* timestampEnd = json_object_dotget_string(entry, "timestampEnd");
        unsigned int value = (unsigned int)json_object_dotget_number(entry, "value");
        // process values
    }
}

区别在于这段代码:json_object_dotget_array(json_value_get_object(root_value), "entries");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2013-03-21
    • 2013-08-27
    • 2016-06-19
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多