Skip to content
Permalink
Browse files

Support encoding lists and maps to json

  • Loading branch information
nyalldawson committed May 6, 2016
1 parent 819ed86 commit 935f4ad21cc9142cc0122138a8f06994668b761d
Showing with 40 additions and 0 deletions.
  1. +34 −0 src/core/qgsjsonutils.cpp
  2. +6 −0 tests/src/python/test_qgsjsonutils.py
@@ -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()
@@ -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 """

0 comments on commit 935f4ad

Please sign in to comment.
You can’t perform that action at this time.