首页 > 解决方案 > 如何从 JSON 的特定数据块中获取数据

问题描述

我正在尝试获取第一个接受的答案 ID。如果我打印出解析的数据,这就是它的样子

{"items":[{"accepted_answer_id":23249538,"question_id":23248046},{"accepted_answer_id":5582009,"question_id":5581697},{"accepted_answer_id":43114369,"question_id":43113569},{"accepted_answer_id":12120575,"question_id":12120425},{"question_id":22162858},{"accepted_answer_id":10101621,"question_id":10101556}]}

我想要的是第一个accepted_answer_id 的号码。所以在这种情况下,我想要的只是 23249538。我该怎么做呢?我正在使用堆栈交换 API 执行此操作。这是为学校分配的任务,我必须在我们的服务器上设置一个工具,当人们提出问题时,如果可用,有人会从堆栈溢出中得到答案。这个数字将使用 CURL 传送到另一个 URL,然后它将为我获取答案并将其打印到终端以供用户使用。我还希望,如果没有接受的答案 ID,它只会终止程序而无法找到用户的答案。


                //actually getting the data
                result = curl_easy_perform(curl);

                //making sure that the curl is ok and worked right
                if(result != CURLE_OK)
                {
                        cout << curl_easy_strerror(result) << endl;
                        return 1;
                }

                //making sure that the website gave info
                int httpCode(0);
                curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
                curl_easy_cleanup(curl);

                //if website worked it will be equal to 200
                if(httpCode == 200)
                {
                        cout << "Sucessful Response From URL" << endl;
                        json data = json::parse(readBuffer);
                        cout << data << endl;


                }
        }

标签: c++json

解决方案


CPP可以使用json库,比如rapidjson(rapidjson比较快)或者jsoncpp等。 https://github.com/Tencent/rapidjson https://github.com/open-source-parsers/jsoncpp


推荐阅读