0

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.)

2
  • I would never assume the format will never change. The JSON structure may never change, but the formatting may. At lease prepare for white spaces between tokens which are totally legal in JSON. Commented Oct 21, 2012 at 15:11
  • What I mean by that is that my entire app is based around parsing that string. That means if the other end should introduce changes, I need to adjust my code regardless. I want to say that there won't be variance between subsequent queries. Commented Oct 21, 2012 at 20:03

1 Answer 1

1

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]); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I think what I wrote was a bit ambiguous. I edited my question to reflect that the arrays aren't literally three elements long but can have arbitrary length.
Does exactly what I wanted! Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.