PDA

View Full Version : Help parsing json based chromium bookmarks files



jiveaxe
20th January 2011, 18:11
Hi, I'm trying to retrieve bookmarks from chrome/chromium; these are stored in a plain text file using json format. Have made some experiments with qjson but the best I got is the first level bookmarks.

Here a sample file: http://paste.kde.org/2933/

This is my (very ugly) code:


QJson::Parser parser;
bool ok;

QVariantMap result = parser.parse(&file, &ok).toMap();
if (!ok) {
ui->plainTextEdit->appendPlainText("An error occurred during parsing");
return;
}

QVariantMap rootsMap = result["roots"].toMap();
QMapIterator<QString, QVariant> i(rootsMap);

while (i.hasNext()) {
i.next();
QVariantMap bookmarkbarMap = rootsMap[i.key()].toMap();
QVariantList childrenMap = bookmarkbarMap["children"].toList();

for(int i = 0; i < childrenMap.size(); i++) {
QVariantMap nestedMap = childrenMap.at(i).toMap();
if(nestedMap["type"].toString()=="url") {
qDebug() << nestedMap["name"].toString();
qDebug() << nestedMap["url"].toString();
qDebug() << "\n";
}
}
}

Have tryed to use only QT as explained here (http://qtwiki.org/Parsing_JSON_with_QT_using_standard_QT_library) (QScriptEngine/QScriptValue) but the examples there are too simple.

Thanks

marcvanriet
20th January 2011, 19:15
Hi,
So does the code above work as expected ? And what have you tried to get the sublevel bookmarks ?

If you include <QDebug> you can do something like this :

qDebug() << nestedMap ;
This will make more clear what kind of data is stored in the variants produced by QJson.

Best regards,
Marc

jiveaxe
21st January 2011, 11:50
Solved. If interested, below the code:


void Dialog::on_pushButton_clicked()
{
QFile file(QDir::homePath() + "/.config/chromium/Default/Bookmarks");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;

QJson::Parser parser;
bool ok;

QVariantMap result = parser.parse(&file, &ok).toMap();
file.close();
if (!ok) {
ui->plainTextEdit->appendPlainText("An error occurred during parsing");
return;
}

QVariantMap rootsMap = result["roots"].toMap();
QMapIterator<QString, QVariant> i(rootsMap);

while (i.hasNext()) {
i.next();
QVariantMap map = rootsMap[i.key()].toMap();
getChildren(map);
}
}

void Dialog::getChildren(const QVariantMap & map) {
QVariantList childrenMap = map["children"].toList();

for(int i = 0; i < childrenMap.size(); i++) {
QVariantMap nestedMap = childrenMap.at(i).toMap();
if(nestedMap["type"].toString()=="url") {
m_name = nestedMap["name"].toString();
m_url = nestedMap["url"].toString();
// do something...
}

if(nestedMap.contains("children"))
getChildren(nestedMap);
}
}