Parse multiple Json



  • Hello,

    I have the same question as in this thread. But I think it is not an option to count the {}brackets.
    At the moment I do something like this:

    QByteArray json_data;
    QJsonDocument doc(QJsonDocument::fromJson(json_data));
    json_data.remove(0, doc.toJson().length());
    

    The problem here is that I don't know the format of the incoming Json. This I try to evaluate with:
    json_data.startsWith("{\"");

    This way is not very good and I hope there is a bettery way to accomplish to parse multiple jsons.



  • Hi,

    in the thread you posted the example text is not a valid JSON.
    What is the source of these data?

    BTW, your solution should work

    QByteArray json_data;
    QList<QJSonDocument> docs;
    
    while(!json_data.isEmpty()) {
      QJsonDocument doc(QJsonDocument::fromJson(json_data));
      json_data.remove(0, doc.toJson().length());
      docs.push_back(doc);
    }
    


  • an other application sends me the data via a tcpconntection. but this application sends many json at one time. when I use QTcpSocket.readAll() I get one long string with many Jsons. so I need a way to devorce this string in many little jsons.



  • Hi,

    usually in TCP is a best practice to do one of the following:

    • Send a header with some sync info (special values, length, ...)
    • Using New-line for text information

    Are you sure there's no special character between JSON objects?
    Keep in mind that

     QJsonDocument doc(QJsonDocument::fromJson(json_data));
     json_data.remove(0, doc.toJson().length());
    

    could not work because QJsonDocument, make some formatting on the string so doc.toJSon().length() could return a value that is not the same you read.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.