Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Support encoding lists and maps to json
  • Loading branch information
nyalldawson committed May 9, 2016
1 parent 819ed86 commit 935f4ad
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/core/qgsjsonutils.cpp
Expand Up @@ -111,6 +111,40 @@ QString QgsJSONUtils::encodeValue( const QVariant &value )
case QVariant::Bool:
return value.toBool() ? "true" : "false";

case QVariant::StringList:
{
QStringList input = value.toStringList();
QStringList output;
Q_FOREACH ( const QString& string, input )
{
output << encodeValue( string );
}
return output.join( "," ).prepend( '[' ).append( ']' );
}

case QVariant::List:
{
QVariantList input = value.toList();
QStringList output;
Q_FOREACH ( const QVariant& v, input )
{
output << encodeValue( v );
}
return output.join( "," ).prepend( '[' ).append( ']' );
}

case QVariant::Map:
{
QMap< QString, QVariant > input = value.toMap();
QStringList output;
QMap< QString, QVariant >::const_iterator it = input.constBegin();
for ( ; it != input.constEnd(); ++it )
{
output << encodeValue( it.key() ) + ':' + encodeValue( it.value() );
}
return output.join( ",\n" ).prepend( '{' ).append( '}' );
}

default:
case QVariant::String:
QString v = value.toString()
Expand Down
6 changes: 6 additions & 0 deletions tests/src/python/test_qgsjsonutils.py
Expand Up @@ -98,6 +98,12 @@ def testEncodeValue(self):
self.assertEqual(QgsJSONUtils.encodeValue('str\\ning'), '"str\\\\ning"')
self.assertEqual(QgsJSONUtils.encodeValue('str\n\\\\ing'), '"str\\n\\\\\\\\ing"')
self.assertEqual(QgsJSONUtils.encodeValue('str/ing'), '"str\\/ing"')
self.assertEqual(QgsJSONUtils.encodeValue([5, 6]), '[5,6]')
self.assertEqual(QgsJSONUtils.encodeValue(['a', 'b', 'c']), '["a","b","c"]')
self.assertEqual(QgsJSONUtils.encodeValue(['a', 3, 'c']), '["a",3,"c"]')
self.assertEqual(QgsJSONUtils.encodeValue(['a', 'c\nd']), '["a","c\\nd"]')
self.assertEqual(QgsJSONUtils.encodeValue({'key': 'value', 'key2': 5}), '{"key":"value",\n"key2":5}')
self.assertEqual(QgsJSONUtils.encodeValue({'key': [1, 2, 3], 'key2': {'nested': 'nested\\result'}}), '{"key":[1,2,3],\n"key2":{"nested":"nested\\\\result"}}')

def testFeatureToGeoJSON(self):
""" test converting features to GeoJSON """
Expand Down

0 comments on commit 935f4ad

Please sign in to comment.