Add text to json C ++

json-c example
create json string in c
json-c api
install json-c
json-c windows
c struct to json
c json serializer
cjson example in c

There is a JSON file, how can I add information there so that the past is left? Did something like this, does not work:

QFile File(pathJSONProject);
File.open(QIODevice::ReadOnly | QIODevice::Text);
QJsonParseError JsonParseError;
QJsonDocument JsonDocument = QJsonDocument::fromJson(File.readAll(), &JsonParseError);

QJsonObject json = JsonDocument.object();

json.insert("Расстояние", dlgOpen->distance);
json.insert("Размер", dlgOpen->size);
json.insert("Путь", pathFolder);
QJsonDocument document(json);
File.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
File.write(document.toJson());
File.close();

I want to add entries to the file. Can't do it. It does not change.

First, is the file like this? How does he have to add new entries?

{
    "Name": "45",
    "Path": "C:/Users/Dmitry/Desktop/45.json"
}

How to add a new entry to the array?

Always handle the return value of QFile::open() to check whether it was successful or not.


There can be multiple ways to insert an array in JSON. Here's an example:

#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

int main()
{
    const auto data = R"({ "Name": "45", "Path": "C:\file.json" })";

    auto doc = QJsonDocument::fromJson( data );
    qDebug() << "BEFORE:\n\n"
             << qPrintable( doc.toJson( QJsonDocument::Indented ) );

    // Create an array and add objects
    const auto obj1 = QJsonObject{ { "name", "abc" }, { "default", 11 } };
    const auto obj2 = QJsonObject{ { "name", "xyz" }, { "default", 22 } };

    auto obj = doc.object();
    obj.insert( "array", QJsonArray{ obj1, obj2 } );

    doc.setObject( obj );
    qDebug() << "\nAFTER:\n"
             << qPrintable( doc.toJson( QJsonDocument::Indented ) );

    // Add more objects to array

    const auto obj3 = QJsonObject
    {
        { "name", "def" },
        { "default", 33 },
        { "new1", "1" },
        { "new2", "2" }     // Add any number of objects...
    };

    const auto obj4 = QJsonObject{ { "name", "jkl" }, { "default", 44 } };

    // Get existing array to append more elements
    auto arr = doc.object()[ "array" ].toArray();
    arr.append( obj3 );
    arr.append( obj4 );

    // Set old array to newly updated one
    obj[ "array" ] = arr;

    doc.setObject( obj );
    qDebug() << "\nAFTER THAT:\n"
             << qPrintable( doc.toJson( QJsonDocument::Indented ) );

    return 0;
}

Output:

BEFORE:

 {
    "Name": "45",
    "Path": "C:\file.json"
}


AFTER:
 {
    "Name": "45",
    "Path": "C:\file.json",
    "array": [
        {
            "default": 11,
            "name": "abc"
        },
        {
            "default": 22,
            "name": "xyz"
        }
    ]
}


AFTER THAT:
 {
    "Name": "45",
    "Path": "C:\file.json",
    "array": [
        {
            "default": 11,
            "name": "abc"
        },
        {
            "default": 22,
            "name": "xyz"
        },
        {
            "default": 33,
            "name": "def",
            "new1": "1",
            "new2": "2"
        },
        {
            "default": 44,
            "name": "jkl"
        }
    ]
}

Also, take a look at QJsonArray::fromStringList() and QJsonArray::fromVariantList().

Examples for the json-c tutorial. � GitHub, A simple example of json string parsing with json-c. The following create an object and add the question and answer to it. */ printf("\nJson in plain text: \n");. The System.Text.Json.Serialization namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization. The code examples shown in this article require using directives for one or both of these namespaces: using System.Text.Json; using System.Text.Json.Serialization;

Check the return value of

File.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);

It's most likely going to be false since you already have the file open for ReadOnly access and haven't closed it.

json-c/json-c, https://github.com/json-c/json-c is the official code repository for json-c. If your system has pkgconfig , then you can just add this to your makefile : When parsing text, the json_tokener object is independent from the json_object that it returns� The System.Text.Json namespace provides high-performance, low-allocating, and standards-compliant capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON text and deserializing JSON text to objects, with UTF-8 support built-in. It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM

To modify the data, given your example, you need to check if the contained data in the QJsonDocument is an array or a simple object. In your case, I suppose you want to append data to an array. Try something like this:

// Read the data
const QString filename = "example.json";
QJsonDocument doc = read(filename);

// Check that it's an array and append new data
if (doc.isArray()) {
    auto array = doc.array();
    array.append(QJsonObject{
        {"Name", "mohabouje"}, {"Path", "whatever"}
    });

    array.append(QJsonObject{
        {"Name", "mojito"}, {"Path", "whatever"}
    });
    doc.setArray(array);
}
// Write the new data
write(filename, doc); 

A helper functions to read/write JSON documents may avoid the mistake of open/closing a file:

QJsonDocument read(const QString& filename) {
    QFile file(filename);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    const QString val = file.readAll();
    file.close();
    return QJsonDocument::fromJson(val.toUtf8());
}

void write(const QString& filename, const QJsonDocument& document) {
    QFile file(filename);
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(document.toJson());
    file.close();
}

System.Text.Json Namespace, It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM) for random access of the JSON� Try adding same json here, it looks like some extra chacters are added to the initial string, which would be hard to remove by JSON parsers. – Pranay Jaiswal Jul 19 '19 at 10:42 add a comment |

The most simple JSON parser in C for small systems, a fast and small JSON tokenizer and parser (sort of) jsmn (pronounced like ' jasmine') is a minimalistic JSON parser in C. It can be easily integrated into the resource-limited projects or It means the following text will be valid for jsmn: There is a CopyTo method on FileStream.So you don't need to read char-by-char, open a file stream and CopyTo to the response stream.. Also I would recommend you to reserialize the file first (using Json.NET, you can simply use dynamic to avoid messing with concrete types), and since it is an array of objects, then add your new object to this array and save it back.

Add JSON string in JSON body, Is there a way I can pass JSON string in the JSON body. Example, Here is my JSON Body, {"description":"Some Text",� Although json-c does not support fully multi-threaded access to object trees, it has some code to help make its use in threaded programs a bit safer. Currently, this is limited to using atomic operations for json_object_get() and json_object_put().

JSON - Quick Guide, JSON or JavaScript Object Notation is a lightweight text-based open standard used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. document.write("<h3>Author = " + object1.author+"</h3>"); var object2� Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON

Comments
  • What exactly doesn't work? Could you show us json file before and after you write it?
  • I want to add entries to the file. Can't do it. It does not change.
  • Close the file after you read the contents, before opening it again in WriteOnly mode.
  • thanks, and how can I add to the record (array)?
  • QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();
  • Thank. And if I then want to open this file and add the same elements to the array to the end.
  • And tell me how then to work with this array? Parsing certain data from it is convenient?
  • @Optimus: Depends on the availability of data. If you already have a complete JSON string you can use fromString family of functions. If you have dynamic data, you can create new and/or manipulate existing objects to populate a new JSON.
  • The data will be constantly updated. but I control it. everyone will have a unique indicator
  • @Optimus: Right. Yes, it is quite convenient once you get the hang of Qt JSON APIs. These are pretty straightforward. If you have something specific beyond the scope of this question, you can look at Qt documentation. And, if you get stuck somewhere, you can always post on SO.