Skip to content

Printing comments from Json file to the console


Complete example on how to print comments from a json file to the console, ordered by date.

post.json
{
    "title": "Now what?!",
    "image": "https://www.heresmyimage.com/6eeIo5zhheElgSuQBRZH.png",
    "comments": [
        {
            "author": "LongjumpingStranger0",
            "timestamp": 1600622509,
            "message": "I think I’ve seen you before"
        },
        {
            "author": "hin2u",
            "timestamp": 1600022509,
            "message": "I'm gonna be honest with you, I'm kinda retarded."
        },
        {
            "author": "angryunfunnyasshole",
            "timestamp": 1600098113,
            "message": "me who was playing offline cuz I have no friend of any kind : yes, mom"
        },
        {
            "author": "Faglerwagen",
            "timestamp": 1600685435,
            "message": "That was just as fun as video games back in the day"
        },
        {
            "author": "DankMemer4222",
            "timestamp": 1600238413,
            "message": "My dad actively encourages me playing Minecraft with my friends, because it’s the only sort of interaction we can really get these days"
        },
        {
            "author": "mtimetraveller",
            "timestamp": 1600471861,
            "message": "Momma needs to learn two words: real-world and virtual-world."
        }
    ]
}
main.cpp (C++):
#include <fstream>
#include <sstream>
#include <iostream>
#include <time.h>
#include "JasonPP.hpp"

// Helper function
std::string ReadFile(const std::string filePath)
{
    std::ifstream ifs;
    ifs.open(filePath);
    if (!ifs.good())
    {
        std::cerr << "Can't read file" << std::endl;
        throw std::exception("no such file");
        std::terminate();
    }
    std::string buf;
    std::stringstream content;
    while (std::getline(ifs, buf))
    {
        content << buf;
    }
    return content.str();
}

// Helper function
std::string FormatTime(time_t unixTime)
{
    tm my_tm;
    localtime_s(&my_tm, &unixTime);
    char buf[256];
    strftime(buf, sizeof(buf), "%d. %b %Y - %H:%M", &my_tm);
    return std::string(buf);
}

using namespace JasonPP;

int main()
{
    // Read the file to a string
    std::string fileContent = ReadFile("post.json");

    // Check if the files json is valid, if not throw an error
    if (IsJsonValid(fileContent))
    {
        // Put the json code into a JasonPP Json object
        Json json;
        json.Parse(fileContent);

        // If you are running a server, it could be beneficial to
        // just put the whole query into a try-catch to prevent a bad
        // query from killing the whole server.
        try
        {
            // Cache the comment array
            JsonArray& comments = json.AsJson.Get("comments").AsArray;

            // Sort the comments by date
            comments.Sort("timestamp", JSON_ARRAY_SORT_MODE::NUM_ASC);

            // Print them out
            for (unsigned int i = 0; i < comments.Size(); i++)
            {
                std::cout << comments[i].AsJson.Get("author").AsString << " [" << FormatTime(comments[i].AsJson.Get("timestamp").AsInt) << "] says:" << std::endl;

                std::cout << comments[i].AsJson.Get("message").AsString << std::endl << std::endl;
            }
        }
        catch (JsonException& e)
        {
            std::cerr << "Failed: " << e.what() << std::endl;
            return -1;
        }

    }
    else            
    {
        std::cerr << "Failed: Invalid json" << std::endl;
        return -1;
    }


    return 0;
}

That's it.