시작은 미미하나 끝은 쥬쥬하리라.

Programming/QT

[QT] Qt4 - QStringList & for문 활용해서 json데이터 값 추출하기

코딩뚜벅이 2024. 1. 18. 22:05

Qt4 QStringList 활용해서 json 데이터 값 추출하기

  • 데이터 추출 코드
  • 결과

데이터 추출 코드

Qt4에서 json 데이터 중에서 원하는 값을 추출하는 코드를 작성해보겠습니다. 특정 API 등을 통해서 이미 데이터를 파싱해서 가져왔다고 가정하겠습니다. 아래는 예시 코드입니다.

 

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QString>
#include <QStringList>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // JSON 데이터를 가상의 예시로 초기화
    QString jsonData = "{ \"lastBuildDate\":\"Thu, 18 Jan 2024 09:28:30 +0900\", \"total\":137675, \"start\":1, \"display\":10, \"items\":[ {\"title\":\"<b>BASEBALL<\\/b>_Baseball_Baseball\", \"link\":\"https:\\/\\/------------------------\", \"description\":\"<b>Baseball<\\/b> is a modern sport that claims to have originated and been established in the United States. Except for the breathing exercises... No matter how hard you try to understand <b>BASEBALL<\\/b>, baseball There is no link that can be connected to the name. And yet... \", \"bloggername\":\"------------------------\", \"bloggerlink\":\"------------------------\" }, {\"title\":\"Play xbox Super Mega <b>Baseball<\\/b> 4\", \"link\":\------------------------\", \"description\":\"Mega <b>Baseball<\\/b> 4) Unfortunately, it is not in Korean, but there is no major difficulty in playing it, so it is simple... Mega <b>Baseball<\\/b> 4) It feels simple. However, when you start, you start with basic practice games and play online... \", \"bloggername\":\"------------------------ }, {\"title\":\"<b>BASEBALL<\\/b>_Baseball_Baseball\", \"link\":\"https:\\/\\/blog.naver.com\\/------------------------\", \"description\":\"<b>Baseball<\\/b> is a modern sport that claims to have originated and been established in the United States. Except for the breathing exercises... No matter how hard you try to understand <b>BASEBALL<\\/b>, baseball There is no link that can be connected to the name. And yet... \", \"bloggername\":\------------------------\", \"bloggerlink\":\"------------------------\", \"postdate\":\"20231017\" }, {\"title\":\"Play xbox Super Mega <b>Baseball<\\/b> 4\", \"link\":\"https:\\/\\/blog.naver.com\\/------------------------\", \"description\":\"Mega <b>Baseball<\\/b> 4) Unfortunately, it is not in Korean, but there is no major difficulty in playing it, so it is simple... Mega <b>Baseball<\\/b> 4) It feels simple. However, when you start, you start with basic practice games and play online... \", \"bloggername\":\"------------------------";

    // "items":[ 의 시작 위치를 찾기
    int startIndex = jsonData.indexOf("\"items\":[");

    if (startIndex != -1) {
        // 시작 위치부터 끝까지의 부분 문자열 추출
        QString itemsSubstring = jsonData.mid(startIndex + 9); // 9는 "\"items\":[" 의 길이

        // "items" 데이터를 포함하는 부분 문자열 추출
        // 닫는 괄호 ']'가 없다면 남은 문자열 전체가 "items" 데이터라고 가정
        QString itemsData = itemsSubstring.endsWith(']') ? itemsSubstring : jsonData.mid(startIndex);

        // "}, {" 기준으로 "items" 데이터를 항목 목록으로 분할
        QStringList itemsList = itemsData.split("}, {", QString::SkipEmptyParts);

        // 항목 목록의 크기 가져오기
        int itemCount = itemsList.size();

        // 전통적인 for 루프를 사용하여 각 항목을 반복
        for (int i = 0; i < itemCount; ++i) {
            // 현재 항목 가져오기
            const QString& item = itemsList.at(i);

            // 각 항목에 누락된 } 추가
            QString currentItem = item;
            if (!currentItem.endsWith('}')) {
                currentItem += '}';
            }

            // 현재 항목을 키-값 쌍 목록으로 분할
            QStringList keyValuePairList = currentItem.split(",", QString::SkipEmptyParts);

            // 키-값 쌍에서 "title" 추출
            QString title;

            // 키-값 쌍에서 "link" 추출
            QString link;

            // 전통적인 for 루프를 사용하여 각 키-값 쌍 반복
            for (int j = 0; j < keyValuePairList.size(); ++j) {
                const QString& pair = keyValuePairList.at(j);

                if (pair.contains("\"title\":")) {
                    // "title"에서 HTML 태그 제거
                    title = pair.section("\"title\":\"", 1, 1).section("\"", 0, 0);
                    title.remove(QRegExp("<[^>]*>"));
                }

                if (pair.contains("\"link\":")) {
                    link = pair.section("\"link\":\"", 1, 1).section("\"", 0, 0);
                }
            }

            // 추출된 "title"과 "link"를 인덱스와 함께 출력
            qDebug() << QString("{ Index=\"%1\", title=\"%2\", link=\"%3\" }").arg(i + 1).arg(title).arg(link);
        }
    } else {
            qDebug() << "\"items\":[ not found in the JSON data.";
    }

    return a.exec();
}

 

 

1. json 데이터를 가상으로 선언했습니다. 저는 이 중에서 'title'과 'link'을 키값으로 가지는 데이터를 추출하겠습니다. 코드의 json 데이터는 저는 실제로 추출한 데이터를 기반으로 하였기 때문에 실제 블로그 이름과 링크가 포함되는 데이터는 '------------------------'로 가렸습니다.

 

2. 해당 json 데이터는 "items\": [ "라는 태그 이후부터 유의미한 아이템 데이터를 가지고 있기 때문에 그 이후부터의 데이터를 가져와 항목 별로 분할하여 QStringList 객체 안에 넣어주었습니다.

 

3. 다시 위의 QStringList의 특정 리스트에서 key값과 value값을 쌍으로 QStringList 객체에 넣어주었습니다.

 

4. key와 Value의 값이 들어있는 리스트 중 title과 link를 key로 가지는 value를 다시 분할하여 이들 데이터만을 다시 하나의 QString으로 병합하여 출력해주었습니다.

 

위 로직은 for문을 사용하여 데이터의 순회를 구현하였지만 Qt5 이상의 버전에서 기본 프레임워크 클래스로 지원하는 <QJson> 클래스를 활용하면 더 쉬운 데이터 추출이 가능합니다. Qt4에서도 기본 지원 옵션이 아닐뿐, 해당 라이브러리를 추가하여 사용하는 것이 가능합니다.

 


 

결과

위의 데이터 추출 및 가공 결과를 qDebug() 메서드를 통해 콘솔창에 출력한 결과입니다.