기계는 거짓말하지 않는다

C++ 문자열에서 JSON 데이터 파싱(parsing) 본문

C++

C++ 문자열에서 JSON 데이터 파싱(parsing)

KillinTime 2024. 7. 30. 20:50

JSON 데이터가 포함된 문자열 또는 출력에서 JSON 데이터만 파싱(parsing) 하는 간단한 예제이다.

jsoncpp 라이브러리가 필요하다.

Ubuntu에서 jsoncpp 라이브러리 설치

sudo apt-get install libjsoncpp-dev
ln -s /usr/include/jsoncpp/json/ /usr/include/json

예제 코드

#include <iostream>
#include <string>
#include <vector>
#include <json/json.h>

// JSON 문자열 파싱
std::vector<std::string> extract_json_strings(const std::string& input_string) {
    std::vector<std::string> json_strings;
    int start_brace_index = -1;
    int end_brace_index = -1;
    int open_brace_count = 0;
    int close_brace_count = 0;
    
    for (size_t i = 0; i < input_string.length(); ++i) {
        char _char = input_string[i];
        if (_char == '{') {
            open_brace_count++;
            if (open_brace_count == 1) {
                start_brace_index = i;
            }
        }
        
        if (_char == '}' && open_brace_count >= 1) {
            close_brace_count++;
            end_brace_index = i;
            if (open_brace_count == close_brace_count) {
                json_strings.push_back(input_string.substr(start_brace_index, end_brace_index - start_brace_index + 1));
                
                start_brace_index = -1;
                end_brace_index = -1;
                open_brace_count = 0;
                close_brace_count = 0;
            }
        }
    }

    if (open_brace_count >= 1 && close_brace_count != 0 && close_brace_count < open_brace_count) {
        json_strings.push_back(input_string.substr(start_brace_index, end_brace_index - start_brace_index + 1));
    }
    
    for (const auto& json_str : json_strings) {
        std::cout << json_str << std::endl;
    }

    return json_strings;
}

// JSON 문자열을 JSON object로 변환
std::vector<Json::Value> parse_json_strings(const std::vector<std::string>& json_strings) {
    std::vector<Json::Value> json_objects;
    Json::CharReaderBuilder readerBuilder;
    std::string errs;

    for (const auto& json_str : json_strings) {
        Json::Value jsonData;
        std::istringstream s(json_str);
        if (Json::parseFromStream(readerBuilder, s, &jsonData, &errs)) {
            json_objects.push_back(jsonData);
        } else {
            std::cerr << "Failed to parse JSON: " << errs << std::endl;
        }
    }

    return json_objects;
}

int main() {
    // JSON 데이터가 포함된 예제 문자열
    char input_string_char[500] = "\
        Starting processing...\n\
        Python output:\n\
        {\"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\"}\n\
        END_JSON\n\
        Processing completed.\n\
        Python ouput: {\"another\": \"json\", \"example\": \"data\"}\n\
    ";


    std::string input_string = std::string(input_string_char);
    std::vector<std::string> json_strings = extract_json_strings(input_string);

    std::vector<Json::Value> json_objects = parse_json_strings(json_strings);

    for (const auto& json_obj : json_objects) {
        std::cout << json_obj.toStyledString() << std::endl;
    }

    return 0;
}

컴파일(Compile)

위 코드를 json_test.cpp로 저장하였다.

gcc -o json_test json_test.cpp -lstdc++ -ljsoncpp

결과

'C++' 카테고리의 다른 글

#ifdef __cplusplus 매크로의 의미  (0) 2024.06.20
깊은 복사 / 얕은 복사  (0) 2021.05.18
vector, priority_queue 정렬 비교  (0) 2021.05.11
Comments