Help parse this json:

{ "meta": { "v":"1.2" ,"p":"259355195" ,"a":103 ,"t":"aaaaaaa" ,"d":1443729008 } ,"data": [ {"i":78585,"f":103,"t":"сообщение1","d":299977900} ,{"i":78584,"f":259,"t":"сообщение2","d":299975624} ,{...} , ... ,{...} ] } 

Those. The data array contains a large number of objects. I use Qt 4.8.6 and the QJson library. It is not clear how to go through the array of objects and parse each of them. Another problem arises in the fact that if the size of the json file is more than 100 kB, the parser does not work (the file that I need to parse takes about 300 kB). What can be done with this?

Update

errorString() returns an empty string, but at the same time if I try to output to qDebug()

 QVariantMap result = jsonParser.parse(sJson.toLocal8Bit(), &ok).toMap(); qDebug() << result["t"].toString(); 

That gets also an empty string.

  • What does errorString() return errorString() parser object, when, in fact, parsing fails with an error? - alexis031182
  • If relative to your data example from a question, then to get t , you need to run: jsonParser.parse(sJson.toLocal8Bit(), &ok).toMap().value("meta").toMap().value("t").toString(); - alexis031182
  • And, in theory, the utf-8 encoding is better to use, i.e. sJson.toUtf8() . - alexis031182
  • @ alexis031182 Please post your comments as an answer. - Nicolas Chabanovsky

1 answer 1

If you sample values ​​according to the example data from the question, for example, to get the element t , you need to change the query string as follows:

 QString val = jsonParser.parse(sJson.toUtf8(),&ok) .toMap().value("meta").toMap().value("t").toString(); 

or

 QString val = jsonParser.parse(sJson.toUtf8(),&ok) .toMap()["meta"].toMap()["t"].toString(); 

Both options are equivalent and they can be safely used even if it turns out in any of the steps that the requested "tree" branch does not exist. In this case, the result of the command is an empty string.

The difference of the value() method from the operator[] at QMap is that for value() , the second argument can be the value that will be returned if the item is not available.

Of course, if the requirement for the speed of the code in question is important, then it makes sense to check the existence of data at each step (for example, using the QMap contains() method), since in the absence of a value, a default constructor will be invoked for each requested element each time.

The data can be searched by the data key using the following construction:

 const QVariantList items = jsonParser.parse(sJson.toUtf8(),&ok) .toMap()["data"].toList(); foreach(const QVariant &item, items) { // Доступ, например, к элементу "f". QString f_val = item.toMap()["f"]; } 

For json data, utf-8 encoding should be used, unless otherwise agreed with the receiving / sending data.