Add text to json C ++ Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!Safely turning a JSON string into an objectHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Why can't Python parse this JSON data?How can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?

Storing hydrofluoric acid before the invention of plastics

How to bypass password on Windows XP account?

When do you get frequent flier miles - when you buy, or when you fly?

Why is "Consequences inflicted." not a sentence?

Why did the rest of the Eastern Bloc not invade Yugoslavia?

Error "illegal generic type for instanceof" when using local classes

String `!23` is replaced with `docker` in command line

How do I keep my slimes from escaping their pens?

How do pianists reach extremely loud dynamics?

How to deal with a team lead who never gives me credit?

How do I stop a creek from eroding my steep embankment?

porting install scripts : can rpm replace apt?

Why did the IBM 650 use bi-quinary?

Why aren't air breathing engines used as small first stages

How widely used is the term Treppenwitz? Is it something that most Germans know?

Sci-Fi book where patients in a coma ward all live in a subconscious world linked together

Single word antonym of "flightless"

Why are there no cargo aircraft with "flying wing" design?

Can an alien society believe that their star system is the universe?

What is a non-alternating simple group with big order, but relatively few conjugacy classes?

Why do people hide their license plates in the EU?

Is it true that "carbohydrates are of no use for the basal metabolic need"?

List *all* the tuples!

English words in a non-english sci-fi novel



Add text to json C ++



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!Safely turning a JSON string into an objectHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Why can't Python parse this JSON data?How can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















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?



enter image description here










share|improve this question
























  • What exactly doesn't work? Could you show us json file before and after you write it?

    – Xplatforms
    Mar 22 at 9:07











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

    – Optimus
    Mar 22 at 9:09






  • 3





    Close the file after you read the contents, before opening it again in WriteOnly mode.

    – Sergio Monteleone
    Mar 22 at 9:11











  • thanks, and how can I add to the record (array)?

    – Optimus
    Mar 22 at 9:14






  • 1





    QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

    – Xplatforms
    Mar 22 at 10:01

















0















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?



enter image description here










share|improve this question
























  • What exactly doesn't work? Could you show us json file before and after you write it?

    – Xplatforms
    Mar 22 at 9:07











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

    – Optimus
    Mar 22 at 9:09






  • 3





    Close the file after you read the contents, before opening it again in WriteOnly mode.

    – Sergio Monteleone
    Mar 22 at 9:11











  • thanks, and how can I add to the record (array)?

    – Optimus
    Mar 22 at 9:14






  • 1





    QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

    – Xplatforms
    Mar 22 at 10:01













0












0








0








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?



enter image description here










share|improve this question
















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?



enter image description here







c++ json qt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 9:21









Azeem

3,11941224




3,11941224










asked Mar 22 at 9:05









OptimusOptimus

1027




1027












  • What exactly doesn't work? Could you show us json file before and after you write it?

    – Xplatforms
    Mar 22 at 9:07











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

    – Optimus
    Mar 22 at 9:09






  • 3





    Close the file after you read the contents, before opening it again in WriteOnly mode.

    – Sergio Monteleone
    Mar 22 at 9:11











  • thanks, and how can I add to the record (array)?

    – Optimus
    Mar 22 at 9:14






  • 1





    QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

    – Xplatforms
    Mar 22 at 10:01

















  • What exactly doesn't work? Could you show us json file before and after you write it?

    – Xplatforms
    Mar 22 at 9:07











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

    – Optimus
    Mar 22 at 9:09






  • 3





    Close the file after you read the contents, before opening it again in WriteOnly mode.

    – Sergio Monteleone
    Mar 22 at 9:11











  • thanks, and how can I add to the record (array)?

    – Optimus
    Mar 22 at 9:14






  • 1





    QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

    – Xplatforms
    Mar 22 at 10:01
















What exactly doesn't work? Could you show us json file before and after you write it?

– Xplatforms
Mar 22 at 9:07





What exactly doesn't work? Could you show us json file before and after you write it?

– Xplatforms
Mar 22 at 9:07













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

– Optimus
Mar 22 at 9:09





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

– Optimus
Mar 22 at 9:09




3




3





Close the file after you read the contents, before opening it again in WriteOnly mode.

– Sergio Monteleone
Mar 22 at 9:11





Close the file after you read the contents, before opening it again in WriteOnly mode.

– Sergio Monteleone
Mar 22 at 9:11













thanks, and how can I add to the record (array)?

– Optimus
Mar 22 at 9:14





thanks, and how can I add to the record (array)?

– Optimus
Mar 22 at 9:14




1




1





QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

– Xplatforms
Mar 22 at 10:01





QJsonDocument doc; QJsonArray arr; arr.append(.......); doc.setArray(arr); doc.toJson();

– Xplatforms
Mar 22 at 10:01












3 Answers
3






active

oldest

votes


















2














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:nn"
<< 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().






share|improve this answer

























  • Thank. And if I then want to open this file and add the same elements to the array to the end.

    – Optimus
    Mar 22 at 10:17






  • 1





    @Optimus: Check the updated example in the answer.

    – Azeem
    Mar 22 at 10:31











  • And tell me how then to work with this array? Parsing certain data from it is convenient?

    – Optimus
    Mar 22 at 10:45






  • 1





    @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.

    – Azeem
    Mar 22 at 10:48






  • 1





    @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.

    – Azeem
    Mar 22 at 11:01


















1














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.






share|improve this answer






























    1














    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

    void write(const QString& filename, const QJsonDocument& document)
    QFile file(filename);
    file.open(QFile::WriteOnly





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296139%2fadd-text-to-json-c%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      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:nn"
      << 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().






      share|improve this answer

























      • Thank. And if I then want to open this file and add the same elements to the array to the end.

        – Optimus
        Mar 22 at 10:17






      • 1





        @Optimus: Check the updated example in the answer.

        – Azeem
        Mar 22 at 10:31











      • And tell me how then to work with this array? Parsing certain data from it is convenient?

        – Optimus
        Mar 22 at 10:45






      • 1





        @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.

        – Azeem
        Mar 22 at 10:48






      • 1





        @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.

        – Azeem
        Mar 22 at 11:01















      2














      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:nn"
      << 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().






      share|improve this answer

























      • Thank. And if I then want to open this file and add the same elements to the array to the end.

        – Optimus
        Mar 22 at 10:17






      • 1





        @Optimus: Check the updated example in the answer.

        – Azeem
        Mar 22 at 10:31











      • And tell me how then to work with this array? Parsing certain data from it is convenient?

        – Optimus
        Mar 22 at 10:45






      • 1





        @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.

        – Azeem
        Mar 22 at 10:48






      • 1





        @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.

        – Azeem
        Mar 22 at 11:01













      2












      2








      2







      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:nn"
      << 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().






      share|improve this answer















      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:nn"
      << 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().







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 23 at 4:29

























      answered Mar 22 at 10:13









      AzeemAzeem

      3,11941224




      3,11941224












      • Thank. And if I then want to open this file and add the same elements to the array to the end.

        – Optimus
        Mar 22 at 10:17






      • 1





        @Optimus: Check the updated example in the answer.

        – Azeem
        Mar 22 at 10:31











      • And tell me how then to work with this array? Parsing certain data from it is convenient?

        – Optimus
        Mar 22 at 10:45






      • 1





        @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.

        – Azeem
        Mar 22 at 10:48






      • 1





        @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.

        – Azeem
        Mar 22 at 11:01

















      • Thank. And if I then want to open this file and add the same elements to the array to the end.

        – Optimus
        Mar 22 at 10:17






      • 1





        @Optimus: Check the updated example in the answer.

        – Azeem
        Mar 22 at 10:31











      • And tell me how then to work with this array? Parsing certain data from it is convenient?

        – Optimus
        Mar 22 at 10:45






      • 1





        @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.

        – Azeem
        Mar 22 at 10:48






      • 1





        @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.

        – Azeem
        Mar 22 at 11:01
















      Thank. And if I then want to open this file and add the same elements to the array to the end.

      – Optimus
      Mar 22 at 10:17





      Thank. And if I then want to open this file and add the same elements to the array to the end.

      – Optimus
      Mar 22 at 10:17




      1




      1





      @Optimus: Check the updated example in the answer.

      – Azeem
      Mar 22 at 10:31





      @Optimus: Check the updated example in the answer.

      – Azeem
      Mar 22 at 10:31













      And tell me how then to work with this array? Parsing certain data from it is convenient?

      – Optimus
      Mar 22 at 10:45





      And tell me how then to work with this array? Parsing certain data from it is convenient?

      – Optimus
      Mar 22 at 10:45




      1




      1





      @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.

      – Azeem
      Mar 22 at 10:48





      @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.

      – Azeem
      Mar 22 at 10:48




      1




      1





      @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.

      – Azeem
      Mar 22 at 11:01





      @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.

      – Azeem
      Mar 22 at 11:01













      1














      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.






      share|improve this answer



























        1














        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.






        share|improve this answer

























          1












          1








          1







          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.






          share|improve this answer













          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 22 at 9:35









          RobbieERobbieE

          3,40221330




          3,40221330





















              1














              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

              void write(const QString& filename, const QJsonDocument& document)
              QFile file(filename);
              file.open(QFile::WriteOnly





              share|improve this answer



























                1














                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

                void write(const QString& filename, const QJsonDocument& document)
                QFile file(filename);
                file.open(QFile::WriteOnly





                share|improve this answer

























                  1












                  1








                  1







                  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

                  void write(const QString& filename, const QJsonDocument& document)
                  QFile file(filename);
                  file.open(QFile::WriteOnly





                  share|improve this answer













                  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

                  void write(const QString& filename, const QJsonDocument& document)
                  QFile file(filename);
                  file.open(QFile::WriteOnly






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 22 at 10:04









                  mohaboujemohabouje

                  2,5611923




                  2,5611923



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296139%2fadd-text-to-json-c%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현