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;
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?
c++ json qt
add a comment |
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?
c++ json qt
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
add a comment |
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?
c++ json qt
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?
c++ json qt
c++ json qt
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
add a comment |
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
add a comment |
3 Answers
3
active
oldest
votes
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().
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 usefromString
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
|
show 3 more comments
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.
add a comment |
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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().
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 usefromString
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
|
show 3 more comments
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().
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 usefromString
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
|
show 3 more comments
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().
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().
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 usefromString
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
|
show 3 more comments
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 usefromString
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
|
show 3 more comments
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.
add a comment |
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.
add a comment |
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.
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.
answered Mar 22 at 9:35
RobbieERobbieE
3,40221330
3,40221330
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Mar 22 at 10:04
mohaboujemohabouje
2,5611923
2,5611923
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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