A simple class for parsing JSON data into a QVariant hierarchy and vice versa.

Related tags

JSON json qt
Overview

The qt-json project is a simple collection of functions for parsing and serializing JSON data to and from QVariant hierarchies.

NOTE: Qt5 introduced a native JSON object class. If you are targeting Qt5, you should use that instead.

HOW TO USE

Parsing JSON

The parser is really easy to use. Let's say we have the following QString of JSON data:

{
  "encoding" : "UTF-8",
  "plug-ins" : [
    "python",
    "c++",
    "ruby"
  ],
  "indent" : {
    "length" : 3,
    "use_space" : true
  }
}

We would first call the parse-function:

#include "json.h"

bool ok;
// json is a QString containing the JSON data
QtJson::JsonObject result = QtJson::parse(json, ok).toMap();

if(!ok) {
  qFatal("An error occurred during parsing");

Assuming the parser completed without errors, we can then go through the hierarchy:

qDebug() << "encoding:" << result["encoding"].toString();
qDebug() << "plugins:";

foreach(QVariant plugin, result["plug-ins"].toList()) {
    qDebug() << "  -" << plugin.toString();
}

QtJson::JsonObject nested = result["indent"].toMap();
qDebug() << "length:" << nested["length"].toInt();
qDebug() << "use_space:" << nested["use_space"].toBool();

The previous code would print out the following:

encoding: "UTF-8"
plugins:
  - "python"
  - "c++"
  - "ruby"
length: 3
use_space: true

Serializing JSON

To write JSON data from Qt object is as simple as creating and assigning data to a QVariantMap/JsonObject:

QtJson::JsonObject contributor;
contributor["name"] = "Luis Gustavo";
contributor["age"] = 22;

QByteArray data = QtJson::serialize(contributor);

The byte array 'data' contains valid JSON data:

{
  "name": "Luis Gustavo",
  "age": 22
}

Serializing JSON pretty-print

By default, the serialization will create a minified version, like following:

{"name":"Luis Gustavo","age":22}

If you are debugging or logging, you may prefer to enable pretty-print mode globally, before serialize:

QtJson::setPrettySerialize(true);

QByteArray data = QtJson::serialize(contributor);
// ...
QByteArray data = QtJson::serialize(other_contributor);

Obviously, you can disable it with:

QtJson::setPrettySerialize(false);

After creating the QVariantMap, you can create a QVariantList/JsonArray and append the QVariantMaps.

QtJson::JsonObject friend1, friend2, friend3;
friend1["id"] = 1;
friend1["name"] = "Mackenzie Hamphrey";

friend2["id"] = 2;
friend2["name"] = "Melanie Molligan";

friend3["id"] = 3;
friend3["name"] = "Sydney Calhoun";

QtJson::JsonArray friends;
friends.append(friend1);
friends.append(friend2);
friends.append(friend3);

QtJson::JsonObject obj;
obj["friends"] = friends;

This way you create a nested structure:

{
    "friends": [
        {
            "id": 1,
            "name": "MackenzieHamphrey"
        },
        {
            "id": 2,
            "name": "MelanieMolligan"
        },
        {
            "id": 3,
            "name": "SydneyCalhoun"
        }
    ]
}

If you continue this process recursively, you nest more levels into the JSON structure.

Using Builders

For simplicity you can use builders, if you prefer.

For example, create a JsonObject:

QtJson::JsonObject json = QtJson::objectBuilder()
    ->set("field_1", 10)
    ->set("field_2", "A string")
    ->set("field_3", true)
    ->set("field_4", QtJson::objectBuilder()
        ->set("sub_field_1", 10.4)
        ->set("sub_field_n", "Another string")
    )
    ->create();

Or create a JsonArray:

QtJson::JsonArray json = QtJson::arrayBuilder()
    ->add(5)
    ->add(90.2)
    ->add(true)
    ->add("anything else")
    ->create();

Take a look at this example that rewrite the previous one:

QtJson::JsonObject obj = QtJson::objectBuilder()
    ->set("friends", QtJson::arrayBuilder()
        ->add(QtJson::objectBuilder()
            ->set("id", 1)
            ->set("name", "Mackenzie Hamphrey")
        )
        ->add(QtJson::objectBuilder()
            ->set("id", 2)
            ->set("name", "Melanie Molligan")
        )
        ->add(QtJson::objectBuilder()
            ->set("id", 3)
            ->set("name", "Sydney Calhoun")
        )
    )
    ->create();

3. CONTRIBUTING

Send in a pull request and bug the maintainer until it gets merged and published. Make sure to add yourself to AUTHORS.

Issues
  • The library will be no longer necessary

    The library will be no longer necessary

    Well,

    The Qt5 will be released in the end of June with many new features such as support for JSON: http://doc.qt.nokia.com/qt5-snapshot/json.html

    In a short time the qt-json library will be no longer necessary and I want to thank anybody who is involved in it.

    opened by gustavosbarreto 8
  • Add QtJson::Object class implementation

    Add QtJson::Object class implementation

    Hello,

    It's useful to me to use json object with json[key] = value semantics. This patch set adds QVariant-based QtJson::Object class that implements such an ability. Now it's possible to use the following:

    QtJson::Object json;
    json["a"] = 0;
    json["b"]["c"] = 1;
    json["b"]["d"] = 2;
    json["b"]["e"]["f"] = QString("hello");
    
    opened by milabs 3
  • Updated Documentation

    Updated Documentation

    replaced readme.txt with markdown version.

    added info regarding nested JSON structure creation

    added note regarding Qt5's native QJsonObject

    Included Qt4.8 class reference links for the classes used in the examples, as well as a link to the example solve by ereilin in stackoverflow

    opened by joum 3
  • Unicode string problem

    Unicode string problem

    Hi,

    I moved from Qt 5.0.2 to Q t4.8.4. On Qt5 I used json parser provided by Qt. On Qt 4.8.4 I needed find own. I like your simple json package. It work fine except unicode strings. I send json via websocket client. I also writting sent json into file. When sending string with special polish characters (like "ść") I see in log file "msg" : "ść" server returns me "msg" : "ść". On QT5 everything worked fine. Need I some extra code to handle unicode? I construct json like this:

    o["msg"] = ui->editMsg->text().toUtf8();
    send(QString(QtJson::serialize(o)));
    

    And "send" function is:

    void send(const QString &msg)
    {
      logg.send("Sent", msg);
      ws->sendUtf8Message(msg.toUtf8());
    }
    

    Regards

    opened by dibok 2
  • Why class?

    Why class?

    Why is QtJson API encapsulated in a class? As far as I know, there are no non-static field in the class, the class has no state, therefore, I'd say it's useless.

    Also, it exposes the private function in .h.

    Why not just leave the public function in QtJson namespace without a class and those private functions as static in the .cpp

    To explain what I mean I'll try attach code/commit...

    opened by vojtechkral 2
  • Update json.h

    Update json.h

    opened by BriFuture 1
  • Reduces spaces

    Reduces spaces

    As the serialized output is not suitable for end-users (due to the lack of newlines and proper indentation), the spaces can be removed too.

    Feel free to close this PR in case it is not in line with the goals of the project.

    opened by george-hopkins 1
  • Added QStringList inclusion.

    Added QStringList inclusion.

    This should fix problems with compilation on OS/2 + Qt4.

    [ 34%] Building CXX object CMakeFiles/rssguard.dir/src/gui/dialogs/formdatabasecleanup.cpp.obj H:/rssguard/src/qt-json/json.cpp: In function 'QVariant QtJson::clone(const QVariant&)': H:/rssguard/src/qt-json/json.cpp:120:37: error: invalid use of incomplete type 'class QStringList' cloneList(v, data.toStringList()); ^ In file included from C:/usr/include/QtCore/qdatetime.h:45:0, from C:/usr/include/QtCore/QDateTime:1, from H:/rssguard/src/qt-json/json.cpp:23: C:/usr/include/QtCore/qstring.h:94:7: error: forward declaration of 'class QStringList' class QStringList; ^ CMakeFiles/rssguard.dir/build.make:714: recipe for target 'CMakeFiles/rssguard.dir/src/qt-json/json.cpp.obj' failed make[2]: *** [CMakeFiles/rssguard.dir/src/qt-json/json.cpp.obj] Error 1 make[2]: *** Waiting for unfinished jobs.... CMakeFiles/Makefile2:128: recipe for target 'CMakeFiles/rssguard.dir/all' failed make[1]: *** [CMakeFiles/rssguard.dir/all] Error 2 Makefile:146: recipe for target 'all' failed make: *** [all] Error 2

    opened by martinrotter 1
  • Wrong conversion to double!

    Wrong conversion to double!

    I tested and found that the use of:

    str = QByteArray::number(value, 'g', 20); //line 123 json.cpp

    is a really problem (eg: 41.32 converted in "41.320000000000000284" !!!!!!!)

    it seems depend on the precision you used (20). Partially(not completely tested) solved in the following way:

    str = QByteArray::number(value, 'g'); //line 123 json.cpp

    Thanks for your nice job.

    opened by cydside 1
  • Use template to serialize QVariantHash and QVariantMap

    Use template to serialize QVariantHash and QVariantMap

    Use template to serialize QVariantHash and QVariantMap, So the code looks cleaner.

    BTW: I suggest expanding tab to spaces, the code otherwise looks strange in editors with different tab setting.

    opened by sunxiaoguang 1
  • Corrected serialization of long values.

    Corrected serialization of long values.

    Shouldn't be calling sanatize string when serializing long values. It adds quotes around the number thus implying it's a string. There shouldn't be anything to santizes anyway.

    opened by klnusbaum 1
  • Looking for a maintainer

    Looking for a maintainer

    I am not the right person to maintain qt-json anymore, actually I haven't been for a long time. I have professionally moved away from the Qt ecosystem and lack the time and passion that I once had for this.

    So any person willing to dedicate a little time for this project please step forward.

    ~I will be moving this repository under the new qt-json organization.~

    opened by gaudecker 0
  • Improve the reliability of the parser

    Improve the reliability of the parser

    See Parsing JSON is a Minefield.

    There is a ton of work to make qt-json pass the test cases in the article. If someone has the time to check them, I'm sure that would be much appreciated by the users.

    contibutor-friendly 
    opened by gaudecker 0
  • Occasionally needed: json parse w/ an ordered QVariantMap, e.g. Prefs dialog setup

    Occasionally needed: json parse w/ an ordered QVariantMap, e.g. Prefs dialog setup

    This can be accomplished by subclassing QVariantMap:

    #ifndef ORDEREDVARIANTMAP_H
    #define ORDEREDVARIANTMAP_H
    
    #include <QtCore>
    
    class OrderedVariantMap : public QMap<QString, QVariant> {
    // Test:
    //    OrderedVariantMap test_map;
    //    test_map.insert("xxx", 1);
    //    test_map.insert("aaa", 2);
    //    test_map.insert("kkk", 3);
    
    //    test_map["321"] = 4;
    //    test_map["000"] = 5;
    //    test_map["123"] = 6;
    
    //    qDebug() << "QMap.keys()" << test_map.keys();
    //    qDebug() << "QMap.orderedKeys()" << test_map.orderedKeys();
    
    //    QVariant test_variant;
    //    test_variant.setValue(test_map);
    //    qDebug() << "test_variant.typeName()" << test_variant.typeName();
    //    OrderedVariantMap test_map_recovered = qvariant_cast<OrderedVariantMap>(test_variant);
    //    qDebug() << "test_map_recovered.orderedKeys()" << test_map_recovered.orderedKeys();
    
    // Test results:
    //    QMap.keys() ("000", "123", "321", "aaa", "kkk", "xxx")
    //    QMap.orderedKeys() ("xxx", "aaa", "kkk", "321", "000", "123")
    //    test_variant.typeName() OrderedVariantMap
    //    test_map_recovered.orderedKeys() ("xxx", "aaa", "kkk", "321", "000", "123")
    
    public:
        OrderedVariantMap ( );
        ~OrderedVariantMap ( );
    
        void
        clear ( );
    
        void // QMap::iterator
        insert ( const QString &key,
                 const QVariant &value );
    
        QVariant&
        operator[] ( const QString &key );
    
        const QVariant
        operator[] ( const QString &key ) const;
    
        const QString
        orderedKey ( int index ) const;
    
        const QVariant
        orderedValue ( int index ) const;
    
        QStringList
        orderedKeys ( ) const ;
    
    private:
        QStringList Ordered_Keys;
    
    protected:
    
    };
    
    Q_DECLARE_METATYPE(OrderedVariantMap)
    
    #endif // ORDEREDVARIANTMAP_H
    
    

    and

    #include "OrderedVariantMap.h"
    
    OrderedVariantMap::OrderedVariantMap ( ) : QMap ( ) {
    
    }
    
    OrderedVariantMap::~OrderedVariantMap ( ) {
    
    }
    
    QStringList
    OrderedVariantMap::orderedKeys ( ) const {
        return Ordered_Keys;
    }
    
    void
    OrderedVariantMap::clear ( ) {
        Ordered_Keys.clear();
        QMap::clear();
    }
    
    void // QMap::iterator
    OrderedVariantMap::insert ( const QString &key,
                                const QVariant &value ) {
        Ordered_Keys.append(key);
        QMap::insert(key, value);
    }
    
    QVariant&
    OrderedVariantMap::operator[] ( const QString &key ) {
        Ordered_Keys.append(key);
        return QMap::operator [](key);
    }
    
    const QVariant
    OrderedVariantMap::operator[] ( const QString &key ) const {
        return this->value(key);
    }
    
    const QString
    OrderedVariantMap::orderedKey ( int index ) const {
        return Ordered_Keys[index];
    }
    
    const QVariant
    OrderedVariantMap::orderedValue ( int index ) const {
        return this->value(Ordered_Keys[index]);
    }
    
    

    I've made the changes to json.h/.cpp which I'll send if you're interested.

    Ken

    kcrossen at mail server gmail.com

    opened by kcrossen 0
  • Too many QString constructions/destructions around

    Too many QString constructions/destructions around

    Hi there, profiler suggests (and it is right this time) that below mentioned methods create myriads of QString temporary instances that can be easily avoided as written below - using static QString instance for the very static contents.

    diff -r 181aa426115e qtjson/json.cpp --- a/qtjson/json.cpp Wed Nov 21 10:04:39 2012 +0100 +++ b/qtjson/json.cpp Wed Nov 21 14:13:44 2012 +0100 @@ -503,11 +503,12 @@ */ int Json::lastIndexOfNumber(const QString &json, int index) {

    • static const QString numericCharacters("0123456789+-.eE"); int lastIndex;
     for(lastIndex = index; lastIndex < json.size(); lastIndex++)
     {
    
    •            if(QString("0123456789+-.eE").indexOf(json[lastIndex]) == -1)
      
    •            if(numericCharacters.indexOf(json[lastIndex]) == -1)
               {
                       break;
               }
      
      @@ -521,9 +522,11 @@ */ void Json::eatWhitespace(const QString &json, int &index) {
    • static const QString whitespaceChars(" \t\n\r");
    • for(; index < json.size(); index++) {
    •            if(QString(" \t\n\r").indexOf(json[index]) == -1)
      
    •            if(whitespaceChars.indexOf(json[index]) == -1)
               {
                       break;
               }
      
    contibutor-friendly 
    opened by JanKovis 0
  • Empty string parses as null string

    Empty string parses as null string

    {
        "action":"EntityHandler",
        "method":"updateParameter",
        "data": [
            "/path/name",
            "text",
            ""
        ],
        "type":"rpc",
        "tid":294
    }
    

    When parsed, "" becomes a null QString, as opposed to an empty QString. The difference is significant. This seems to be an issue in Json::parseString, where the initial result string is created as QString s, rather than QString s("") or QString s = "".

    contibutor-friendly 
    opened by Mzyxptlk 3
json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa

Structurize your JSON json_struct is a single header only library that parses JSON to C++ structs/classes and serializing structs/classes to JSON. It

Jørgen Lind 238 Aug 6, 2022
A C++, header-only library for constructing JSON and JSON-like data formats, with JSON Pointer, JSON Patch, JSON Schema, JSONPath, JMESPath, CSV, MessagePack, CBOR, BSON, UBJSON

JSONCONS jsoncons is a C++, header-only library for constructing JSON and JSON-like data formats such as CBOR. For each supported data format, it enab

Daniel Parker 510 Aug 1, 2022
https://github.com/json-c/json-c is the official code repository for json-c. See the wiki for release tarballs for download. API docs at http://json-c.github.io/json-c/

\mainpage json-c Overview and Build Status Building on Unix Prerequisites Build commands CMake options Testing Building with vcpkg Linking to libjson-

json-c 2.5k Aug 13, 2022
QJson is a qt-based library that maps JSON data to QVariant objects.

QJson JSON (JavaScript Object Notation) is a lightweight data-interchange format. It can represents integer, real number, string, an ordered sequence

Flavio Castelli 268 Aug 8, 2022
A convenience C++ wrapper library for JSON-Glib providing friendly syntactic sugar for parsing JSON

This library is a wrapper for the json-glib library that aims to provide the user with a trivial alternative API to the API provided by the base json-

Rob J Meijer 16 May 10, 2022
json2cpp is compiles a json file into static constexpr data structures that can be used at compile time or runtime

json2cpp json2cpp is compiles a json file into static constexpr data structures that can be used at compile time or runtime. Features Literally 0 runt

Jason Turner 162 Aug 6, 2022
An easy-to-use and competitively fast JSON parsing library for C++17, forked from Bitcoin Cash Node's own UniValue library.

UniValue JSON Library for C++17 (and above) An easy-to-use and competitively fast JSON parsing library for C++17, forked from Bitcoin Cash Node's own

Calin Culianu 10 Aug 31, 2021
Fast JSON serialization and parsing in C++

DAW JSON Link v2 Content Intro Default Mapping of Types API Documentation - Member mapping classes and methods Cookbook Get cooking and putting it all

Darrell Wright 305 Aug 5, 2022
Jvar - JS inspired Variants and JSON parsing for C++

jvar jvar tries to capture some of the expressiveness of JavaScript and bring it into C++ In particular, it implements a Variant type which is similar

Yasser Asmi 23 Jun 15, 2022
jstruct is an automatic C code generation tool for generating JSON parsing and stringifying code.

jstruct is an automatic C code generation tool for generating JSON parsing and stringifying code. The C code generated by this tool needs to depend on the cJSON library for execution.

acoinfo 27 Apr 18, 2022
Parsing gigabytes of JSON per second

simdjson : Parsing gigabytes of JSON per second JSON is everywhere on the Internet. Servers spend a *lot* of time parsing it. We need a fresh approach

null 15.9k Aug 11, 2022
A fast streaming JSON parsing library in C.

********************************************************************** This is YAJL 2. For the legacy version of YAJL see https

Lloyd Hilaiel 2.1k Aug 10, 2022
Very fast Python JSON parsing library

cysimdjson Fast JSON parsing library for Python, 7-12 times faster than standard Python JSON parser. It is Python bindings for the simdjson using Cyth

TeskaLabs 215 Aug 5, 2022
Parsing gigabytes of JSON per second

simdjson : Parsing gigabytes of JSON per second JSON is everywhere on the Internet. Servers spend a *lot* of time parsing it. We need a fresh approach

null 15.9k Aug 8, 2022
This is a JSON C++ library. It can write and read JSON files with ease and speed.

Json Box JSON (JavaScript Object Notation) is a lightweight data-interchange format. Json Box is a C++ library used to read and write JSON with ease a

Anhero inc. 108 Jul 7, 2022
json-cpp is a C++11 JSON serialization library.

JSON parser and generator for C++ Version 0.1 alpha json-cpp is a C++11 JSON serialization library. Example #include <json-cpp.hpp> struct Foo {

Anatoly Scheglov 4 Dec 31, 2019
json-build is a zero-allocation JSON serializer compatible with C89

json-build is a zero-allocation JSON serializer compatible with C89. It is inspired by jsmn, a minimalistic JSON tokenizer.

Lucas Müller 27 Jul 26, 2022
Convert YouTube Subscriptions JSON into RSS Reader Compatible OPML

OPMLify Convert YouTube Subscriptions JSON into RSS Reader Compatible OPML Brief Overview OPMLify allows you to import your YouTube Subscriptions to a

null 13 May 25, 2022
A Simple Nastran to JSON mesh reader which makes it easy to exchange data

Nastran to Json Converter A simple code that helps convert Nastran meshes to a JSON file format that is more suitable for the current day and age. Cur

Vijai Kumar S 5 Sep 23, 2021