A JSON file stores data objects in JavaScript Object Notation(JSON) format. It’s lightweight and readable, the developer uses it to transmit simple data.
The article shows how to create and read the JSON file in the Qt environment. I planed to save two books’ information to a simple JSON file in the following example.

Write Data To JSON File

1. Create a single book QJsonObject object

Create a QJsonObject object which contains key-value pairs, it can be used to store name and price information of books.
Add struct Book in the program to help to write C++ code.

struct Book
{
    string name;
    double price;
    Book( string _name, double _price )
    {
        name = _name;
        price = _price;
    }
};

//...

    Book obj1( "high school mathematics", 12 );
    QJsonObject book1;
    book1.insert( "name", obj1.name.c_str() );
    book1.insert( "price", obj1.price );

    Book obj2( "advanced high school mathematics", 14 );
    QJsonObject book2;
    book2.insert( "name", obj2.name.c_str() );
    book2.insert( "price", obj2.price );

2. Collect Single Books To Form The Main QJsonObject

Put all single QJsonObject objects to an independent one.

    QJsonObject content;
    content.insert( "book1", book1 );
    content.insert( "book2", book2 );

3. Write To Local JSON File

Use QJsonDocument to convert the main QJsonObject object to text stream.

    QJsonDocument document;
    document.setObject( content );
    QByteArray bytes = document.toJson( QJsonDocument::Indented );
    QFile file( path );
    if( file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
    {
        QTextStream iStream( &file );
        iStream.setCodec( "utf-8" );
        iStream << bytes;
        file.close();
    }
    else
    {
        cout << "file open failed: " << path.toStdString() << endl;
    }

Read JSON File

1. Open File And Read Data

The QJsonDocument and QFile and help us to open the JSON file and store data to the JSON object.

    if( file.open( QIODevice::ReadOnly ) )
    {
        QByteArray bytes = file.readAll();
        file.close();

        QJsonParseError jsonError;
        QJsonDocument document = QJsonDocument::fromJson( bytes, &jsonError );
        if( jsonError.error != QJsonParseError::NoError )
        {
            cout << "fromJson failed: " << jsonError.errorString().toStdString() << endl;
            return ;
        }
        if( document.isObject() )
        {
            QJsonObject jsonObj = document.object();
        //...
     }

2. Analyze The Main JSON Object

Judge whether the father Json Object contains the target key, take the relevant value, and convert to the JSON object if it exists.
Then read all key-value pairs in the child JSON object.

            QJsonObject jsonObj = document.object();
            QStringList books;
            books << "book1" << "book2";
            for( auto book: books )
            {
                if( jsonObj.contains( book ) )
                {
                    QJsonObject obj = jsonObj.value( book ).toObject();
                    QStringList keys = obj.keys();
                    for( auto key: keys )
                    {
                        auto value = obj.take( key );
                        if( value.isDouble() )
                        {
                            qDebug() << key << " : " << value.toDouble();
                        }
                        else if( value.isString() )
                        {
                            qDebug() << key << " : " << value.toString();
                        }

                    }
                }
            }

All Test Code

Here is the complete source code for all the above steps.

#include <QtXml>
#include <QtCore>
#include <iostream>
#include <QIODevice>

using namespace std;

struct Book
{
    string name;
    double price;
    Book( string _name, double _price )
    {
        name = _name;
        price = _price;
    }
};

void CreateJson(const QString &path)
{
    Book obj1( "high school mathematics", 12 );
    QJsonObject book1;
    book1.insert( "name", obj1.name.c_str() );
    book1.insert( "price", obj1.price );

    Book obj2( "advanced high school mathematics", 14 );
    QJsonObject book2;
    book2.insert( "name", obj2.name.c_str() );
    book2.insert( "price", obj2.price );

    QJsonObject content;
    content.insert( "book1", book1 );
    content.insert( "book2", book2 );

    QJsonDocument document;
    document.setObject( content );
    QByteArray bytes = document.toJson( QJsonDocument::Indented );
    QFile file( path );
    if( file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
    {
        QTextStream iStream( &file );
        iStream.setCodec( "utf-8" );
        iStream << bytes;
        file.close();
    }
    else
    {
        cout << "file open failed: " << path.toStdString() << endl;
    }
}

void ReadJson(const QString &path)
{
    QFile file( path );
    if( file.open( QIODevice::ReadOnly ) )
    {
        QByteArray bytes = file.readAll();
        file.close();

        QJsonParseError jsonError;
        QJsonDocument document = QJsonDocument::fromJson( bytes, &jsonError );
        if( jsonError.error != QJsonParseError::NoError )
        {
            cout << "fromJson failed: " << jsonError.errorString().toStdString() << endl;
            return ;
        }
        if( document.isObject() )
        {
            QJsonObject jsonObj = document.object();
            QStringList books;
            books << "book1" << "book2";
            for( auto book: books )
            {
                if( jsonObj.contains( book ) )
                {
                    QJsonObject obj = jsonObj.value( book ).toObject();
                    QStringList keys = obj.keys();
                    for( auto key: keys )
                    {
                        auto value = obj.take( key );
                        if( value.isDouble() )
                        {
                            qDebug() << key << " : " << value.toDouble();
                        }
                        else if( value.isString() )
                        {
                            qDebug() << key << " : " << value.toString();
                        }

                    }
                }
            }
        }
    }
}

int main(int argc,char **argv)
{
    QString path = "/Users/weiyang/Desktop/test.json";
    CreateJson( path );
    ReadJson( path );
    return 0;
}

Output:

"name"  :  "high school mathematics"
"price"  :  12
"name"  :  "advanced high school mathematics"
"price"  :  14

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Keto Supplment DHEA is a hormone with this increasing a close relative for this DHEA. But there is a major difference between these twos is that 7-Express Keto DHEA […]

Yusuf
2 years ago

Thanks. 🙂

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
2
0
Would love your thoughts, please comment.x
()
x