Search code examples
jsonqtstring-parsing

Parse specific format json array in Qt4, no external libraries


I need extract data from a JSON array, format '[[[1,2,3]],[[1,2,3],[1,2,3]],"string"]' in Qt. logically it's '[[[x-values]],[[y1-values],[y2-values]],"comments"]'.

Edit: x,y1,y2 arrays can be up to 1000+ elements large.

I know that that's the exact format (without the single quotes) and that it's not going to change.

What I really want is QVector xval, y1val; .

How would I parse that?

(I'm new to Qt so please forgive me if I'm missing the obvious.)


Solution

  • Quick and dirty solution:

    QString s = "[[[1,2,3]],[[4,5,6],[7,8,9]],\"string\"]";
    QStringList parts = s.remove("[").remove("]").split(',');
    
    QVector<int> xval, yval;
    if (parts.size() >= 6)
    {
        xval << parts[0].toInt() << parts[1].toInt() << parts[2].toInt();
        yval << parts[3].toInt() << parts[4].toInt() << parts[5].toInt();
    }
    

    Edit: Now supporting variable length arrays:

    QVector<int> ToIntList(const QString& s)
    {
        QVector<int> result;
        QStringList parts = s.trimmed().split(",");
        for (int i = 0; i < parts.size(); ++i)
            result << parts[i].toInt();
        return result;
    }
    
    QString s = "[[[1,2,3,4,5,6, 7,  8]],[[9\n,10], [11,12,13]],\"string\"]";
    QStringList lists = s.remove(" ").split("],[");
    
    for (int i = 0; i < lists.size(); ++i)
        lists[i] = lists[i].remove("[").remove("]");
    
    QVector<int> xval, yval;
    if (lists.size() >= 2)
    {
        xval = ToIntList(lists[0]);
        yval = ToIntList(lists[1]);
    }