unexplored
unexplored

Reputation: 1424

Qt: QScriptValueIterator has an extra element

I am trying to read JSON objects using the QScriptValue class in Qt and I've noticed that when iterating over an array I always get an extra element at the end.

Let's say I have a string named value like this:

QString value = "{\"identifier\":\"testID\", \"params\":[{\"field\":\"filed1:\", \"datatype\":\"integer\",\"fieldend\":\" \"},{\"field\":\"field2: \",\"datatype\":\"integer\",\"fieldend\":\" \"}]}";

My code for iteration looks like this:

QScriptValue sc;
QScriptEngine engine;
sc = engine.evaluate("("+value+")");

if(sc.isValid())
{
    if(sc.property("params").isArray())
    {
        QScriptValueIterator it(sc.property("params"));

        while(it.hasNext())
        {
            it.next();

            qDebug()<< "field:" << it.value().property("field").toString();
            qDebug()<< "datatype:" << it.value().property("datatype").toString();
            qDebug()<< "fieldend:" << it.value().property("fieldend").toString();
            qDebug()<< "--------------";
        }

    }
}

The output results with an extra element that has empty values:

field:  "field1:"
datatype:  "integer"
fieldend:  " "
--------------
field:  "field2: "
datatype:  "integer"
fieldend:  " "
--------------
field:  ""
datatype:  ""
fieldend:  ""
--------------

I read the documentation of QScriptValueIterator and it says:

The next() advances the iterator. The name(), value() and flags() functions return the name, value and flags of the last item that was jumped over

So I changed my iteration accordingly:

while(it.hasNext())
{
    it.next();
    qDebug() << it.name() << " : " << it.value().toString();
    qDebug()<< "--------------";
}

But I get something that I did not expect:

"0"  :  "[object Object]"
--------------
"1"  :  "[object Object]"
--------------
"length"  :  "2"
--------------

Can anyone point out what am I doing wrong here?

Thanks.

Upvotes: 1

Views: 386

Answers (1)

Istvan Keri
Istvan Keri

Reputation: 36

I faced the same issue and I added this line after the it.next(); line: if (it.flags() & QScriptValue::SkipInEnumeration) continue; You can find more info about it here: http://developer.qt.nokia.com/doc/qt-4.8/qscriptvalueiterator.html#details

Upvotes: 2

Related Questions