QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsjsonutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsjsonutils.h
3 -------------
4 Date : May 206
5 Copyright : (C) 2016 Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsjsonutils.h"
17#include "qgsfeatureiterator.h"
18#include "qgsogrutils.h"
19#include "qgsgeometry.h"
20#include "qgsvectorlayer.h"
21#include "qgsrelation.h"
22#include "qgsrelationmanager.h"
23#include "qgsproject.h"
24#include "qgsexception.h"
25#include "qgslogger.h"
27#include "qgsfieldformatter.h"
28#include "qgsapplication.h"
29#include "qgsfeatureid.h"
30#include "qgslinestring.h"
31#include "qgsmultipoint.h"
32#include "qgsmultilinestring.h"
33#include "qgspolygon.h"
34#include "qgsmultipolygon.h"
35
36#include <QJsonDocument>
37#include <QJsonArray>
38#include <QTextCodec>
39#include <nlohmann/json.hpp>
40
42 : mPrecision( precision )
43 , mLayer( vectorLayer )
44{
45 if ( vectorLayer )
46 {
47 mCrs = vectorLayer->crs();
48 mTransform.setSourceCrs( mCrs );
49 }
50
51 // Default 4326
52 mDestinationCrs = QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) );
53 mTransform.setDestinationCrs( mDestinationCrs );
54}
55
57{
58 mLayer = vectorLayer;
59 if ( vectorLayer )
60 {
61 mCrs = vectorLayer->crs();
62 mTransform.setSourceCrs( mCrs );
63 }
64}
65
67{
68 return mLayer.data();
69}
70
72{
73 mCrs = crs;
74 mTransform.setSourceCrs( mCrs );
75}
76
78{
79 return mCrs;
80}
81
82QString QgsJsonExporter::exportFeature( const QgsFeature &feature, const QVariantMap &extraProperties,
83 const QVariant &id, int indent ) const
84{
85 return QString::fromStdString( exportFeatureToJsonObject( feature, extraProperties, id ).dump( indent ) );
86}
87
88json QgsJsonExporter::exportFeatureToJsonObject( const QgsFeature &feature, const QVariantMap &extraProperties, const QVariant &id ) const
89{
90 json featureJson
91 {
92 { "type", "Feature" },
93 };
94 if ( id.isValid() )
95 {
96 bool ok = false;
97 auto intId = id.toLongLong( &ok );
98 if ( ok )
99 {
100 featureJson["id"] = intId;
101 }
102 else
103 {
104 featureJson["id"] = id.toString().toStdString();
105 }
106 }
107 else if ( FID_IS_NULL( feature.id() ) )
108 {
109 featureJson["id"] = nullptr;
110 }
111 else
112 {
113 featureJson["id"] = feature.id();
114 }
115
116 QgsGeometry geom = feature.geometry();
117 if ( !geom.isNull() && mIncludeGeometry )
118 {
119 if ( mCrs.isValid() )
120 {
121 try
122 {
123 QgsGeometry transformed = geom;
124 if ( mTransformGeometries && transformed.transform( mTransform ) == Qgis::GeometryOperationResult::Success )
125 geom = transformed;
126 }
127 catch ( QgsCsException &cse )
128 {
129 Q_UNUSED( cse )
130 }
131 }
132 QgsRectangle box = geom.boundingBox();
133
135 {
136 featureJson[ "bbox" ] =
137 {
138 qgsRound( box.xMinimum(), mPrecision ),
139 qgsRound( box.yMinimum(), mPrecision ),
140 qgsRound( box.xMaximum(), mPrecision ),
141 qgsRound( box.yMaximum(), mPrecision )
142 };
143 }
144 featureJson[ "geometry" ] = geom.asJsonObject( mPrecision );
145 }
146 else
147 {
148 featureJson[ "geometry" ] = nullptr;
149 }
150
151 // build up properties element
152 json properties;
153 if ( mIncludeAttributes || !extraProperties.isEmpty() )
154 {
155 //read all attribute values from the feature
156 if ( mIncludeAttributes )
157 {
158 QgsFields fields = mLayer ? mLayer->fields() : feature.fields();
159 // List of formatters through we want to pass the values
160 QStringList formattersAllowList;
161 formattersAllowList << QStringLiteral( "KeyValue" )
162 << QStringLiteral( "List" )
163 << QStringLiteral( "ValueRelation" )
164 << QStringLiteral( "ValueMap" );
165
166 for ( int i = 0; i < fields.count(); ++i )
167 {
168 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
169 continue;
170
171 QVariant val = feature.attributes().at( i );
172
173 if ( mLayer )
174 {
175 const QgsEditorWidgetSetup setup = fields.at( i ).editorWidgetSetup();
177 if ( formattersAllowList.contains( fieldFormatter->id() ) )
178 val = fieldFormatter->representValue( mLayer.data(), i, setup.config(), QVariant(), val );
179 }
180
181 QString name = fields.at( i ).name();
182 if ( mAttributeDisplayName )
183 {
184 name = mLayer->attributeDisplayName( i );
185 }
186 properties[ name.toStdString() ] = QgsJsonUtils::jsonFromVariant( val );
187 }
188 }
189
190 if ( !extraProperties.isEmpty() )
191 {
192 QVariantMap::const_iterator it = extraProperties.constBegin();
193 for ( ; it != extraProperties.constEnd(); ++it )
194 {
195 properties[ it.key().toStdString() ] = QgsJsonUtils::jsonFromVariant( it.value() );
196 }
197 }
198
199 // related attributes
200 if ( mLayer && mIncludeRelatedAttributes )
201 {
202 QList< QgsRelation > relations = QgsProject::instance()->relationManager()->referencedRelations( mLayer.data() );
203 for ( const auto &relation : std::as_const( relations ) )
204 {
205 QgsFeatureRequest req = relation.getRelatedFeaturesRequest( feature );
207 QgsVectorLayer *childLayer = relation.referencingLayer();
208 json relatedFeatureAttributes;
209 if ( childLayer )
210 {
211 QgsFeatureIterator it = childLayer->getFeatures( req );
212 QVector<QVariant> attributeWidgetCaches;
213 int fieldIndex = 0;
214 const QgsFields fields { childLayer->fields() };
215 for ( const QgsField &field : fields )
216 {
217 QgsEditorWidgetSetup setup = field.editorWidgetSetup();
219 attributeWidgetCaches.append( fieldFormatter->createCache( childLayer, fieldIndex, setup.config() ) );
220 fieldIndex++;
221 }
222 QgsFeature relatedFet;
223 while ( it.nextFeature( relatedFet ) )
224 {
225 relatedFeatureAttributes += QgsJsonUtils::exportAttributesToJsonObject( relatedFet, childLayer, attributeWidgetCaches );
226 }
227 }
228 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
229 }
230 }
231 }
232 featureJson[ "properties" ] = properties;
233 return featureJson;
234}
235
236QString QgsJsonExporter::exportFeatures( const QgsFeatureList &features, int indent ) const
237{
238 return QString::fromStdString( exportFeaturesToJsonObject( features ).dump( indent ) );
239}
240
242{
243 json data
244 {
245 { "type", "FeatureCollection" },
246 { "features", json::array() }
247 };
248 for ( const QgsFeature &feature : std::as_const( features ) )
249 {
250 data["features"].push_back( exportFeatureToJsonObject( feature ) );
251 }
252 return data;
253}
254
256{
257 mDestinationCrs = destinationCrs;
258 mTransform.setDestinationCrs( mDestinationCrs );
259}
260
261//
262// QgsJsonUtils
263//
264
265QgsFeatureList QgsJsonUtils::stringToFeatureList( const QString &string, const QgsFields &fields, QTextCodec *encoding )
266{
267 if ( !encoding )
268 encoding = QTextCodec::codecForName( "UTF-8" );
269
270 return QgsOgrUtils::stringToFeatureList( string, fields, encoding );
271}
272
273QgsFields QgsJsonUtils::stringToFields( const QString &string, QTextCodec *encoding )
274{
275 if ( !encoding )
276 encoding = QTextCodec::codecForName( "UTF-8" );
277
278 return QgsOgrUtils::stringToFields( string, encoding );
279}
280
281QString QgsJsonUtils::encodeValue( const QVariant &value )
282{
283 if ( QgsVariantUtils::isNull( value ) )
284 return QStringLiteral( "null" );
285
286 switch ( value.type() )
287 {
288 case QVariant::Int:
289 case QVariant::UInt:
290 case QVariant::LongLong:
291 case QVariant::ULongLong:
292 case QVariant::Double:
293 return value.toString();
294
295 case QVariant::Bool:
296 return value.toBool() ? "true" : "false";
297
298 case QVariant::StringList:
299 case QVariant::List:
300 case QVariant::Map:
301 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
302
303 default:
304 case QVariant::String:
305 QString v = value.toString()
306 .replace( '\\', QLatin1String( "\\\\" ) )
307 .replace( '"', QLatin1String( "\\\"" ) )
308 .replace( '\r', QLatin1String( "\\r" ) )
309 .replace( '\b', QLatin1String( "\\b" ) )
310 .replace( '\t', QLatin1String( "\\t" ) )
311 .replace( '/', QLatin1String( "\\/" ) )
312 .replace( '\n', QLatin1String( "\\n" ) );
313
314 return v.prepend( '"' ).append( '"' );
315 }
316}
317
318QString QgsJsonUtils::exportAttributes( const QgsFeature &feature, QgsVectorLayer *layer, const QVector<QVariant> &attributeWidgetCaches )
319{
320 QgsFields fields = feature.fields();
321 QString attrs;
322 for ( int i = 0; i < fields.count(); ++i )
323 {
324 if ( i > 0 )
325 attrs += QLatin1String( ",\n" );
326
327 QVariant val = feature.attributes().at( i );
328
329 if ( layer )
330 {
331 QgsEditorWidgetSetup setup = layer->fields().at( i ).editorWidgetSetup();
333 if ( fieldFormatter != QgsApplication::fieldFormatterRegistry()->fallbackFieldFormatter() )
334 val = fieldFormatter->representValue( layer, i, setup.config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
335 }
336
337 attrs += encodeValue( fields.at( i ).name() ) + ':' + encodeValue( val );
338 }
339 return attrs.prepend( '{' ).append( '}' );
340}
341
342QVariantList QgsJsonUtils::parseArray( const QString &json, QVariant::Type type )
343{
344 QString errorMessage;
345 QVariantList result;
346 try
347 {
348 const auto jObj( json::parse( json.toStdString() ) );
349 if ( ! jObj.is_array() )
350 {
351 throw json::parse_error::create( 0, 0, QStringLiteral( "JSON value must be an array" ).toStdString() );
352 }
353 for ( const auto &item : jObj )
354 {
355 // Create a QVariant from the array item
356 QVariant v;
357 if ( item.is_number_integer() )
358 {
359 v = item.get<int>();
360 }
361 else if ( item.is_number_unsigned() )
362 {
363 v = item.get<unsigned>();
364 }
365 else if ( item.is_number_float() )
366 {
367 // Note: it's a double and not a float on purpose
368 v = item.get<double>();
369 }
370 else if ( item.is_string() )
371 {
372 v = QString::fromStdString( item.get<std::string>() );
373 }
374 else if ( item.is_boolean() )
375 {
376 v = item.get<bool>();
377 }
378 else if ( item.is_null() )
379 {
380 // Fallback to int
381 v = QVariant( type == QVariant::Type::Invalid ? QVariant::Type::Int : type );
382 }
383
384 // If a destination type was specified (it's not invalid), try to convert
385 if ( type != QVariant::Invalid )
386 {
387 if ( ! v.convert( static_cast<int>( type ) ) )
388 {
389 QgsLogger::warning( QStringLiteral( "Cannot convert json array element to specified type, ignoring: %1" ).arg( v.toString() ) );
390 }
391 else
392 {
393 result.push_back( v );
394 }
395 }
396 else
397 {
398 result.push_back( v );
399 }
400 }
401 }
402 catch ( json::parse_error &ex )
403 {
404 errorMessage = ex.what();
405 QgsLogger::warning( QStringLiteral( "Cannot parse json (%1): %2" ).arg( ex.what(), json ) );
406 }
407
408 return result;
409}
410
411std::unique_ptr< QgsPoint> parsePointFromGeoJson( const json &coords )
412{
413 if ( !coords.is_array() || coords.size() < 2 || coords.size() > 3 )
414 {
415 QgsDebugError( QStringLiteral( "JSON Point geometry coordinates must be an array of two or three numbers" ) );
416 return nullptr;
417 }
418
419 const double x = coords[0].get< double >();
420 const double y = coords[1].get< double >();
421 if ( coords.size() == 2 )
422 {
423 return std::make_unique< QgsPoint >( x, y );
424 }
425 else
426 {
427 const double z = coords[2].get< double >();
428 return std::make_unique< QgsPoint >( x, y, z );
429 }
430}
431
432std::unique_ptr< QgsLineString> parseLineStringFromGeoJson( const json &coords )
433{
434 if ( !coords.is_array() || coords.size() < 2 )
435 {
436 QgsDebugError( QStringLiteral( "JSON LineString geometry coordinates must be an array of at least two points" ) );
437 return nullptr;
438 }
439
440 const std::size_t coordsSize = coords.size();
441
442 QVector< double > x;
443 QVector< double > y;
444 QVector< double > z;
445#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
446 x.resize( static_cast< int >( coordsSize ) );
447 y.resize( static_cast< int >( coordsSize ) );
448 z.resize( static_cast< int >( coordsSize ) );
449#else
450 x.resize( coordsSize );
451 y.resize( coordsSize );
452 z.resize( coordsSize );
453#endif
454 double *xOut = x.data();
455 double *yOut = y.data();
456 double *zOut = z.data();
457 bool hasZ = false;
458 for ( const auto &coord : coords )
459 {
460 if ( !coord.is_array() || coord.size() < 2 || coord.size() > 3 )
461 {
462 QgsDebugError( QStringLiteral( "JSON LineString geometry coordinates must be an array of two or three numbers" ) );
463 return nullptr;
464 }
465
466 *xOut++ = coord[0].get< double >();
467 *yOut++ = coord[1].get< double >();
468 if ( coord.size() == 3 )
469 {
470 *zOut++ = coord[2].get< double >();
471 hasZ = true;
472 }
473 else
474 {
475 *zOut++ = std::numeric_limits< double >::quiet_NaN();
476 }
477 }
478
479 return std::make_unique< QgsLineString >( x, y, hasZ ? z : QVector<double>() );
480}
481
482std::unique_ptr< QgsPolygon > parsePolygonFromGeoJson( const json &coords )
483{
484 if ( !coords.is_array() || coords.size() < 1 )
485 {
486 QgsDebugError( QStringLiteral( "JSON Polygon geometry coordinates must be an array" ) );
487 return nullptr;
488 }
489
490 const std::size_t coordsSize = coords.size();
491 std::unique_ptr< QgsLineString > exterior = parseLineStringFromGeoJson( coords[0] );
492 if ( !exterior )
493 {
494 return nullptr;
495 }
496
497 std::unique_ptr< QgsPolygon > polygon = std::make_unique< QgsPolygon >( exterior.release() );
498 for ( std::size_t i = 1; i < coordsSize; ++i )
499 {
500 std::unique_ptr< QgsLineString > ring = parseLineStringFromGeoJson( coords[i] );
501 if ( !ring )
502 {
503 return nullptr;
504 }
505 polygon->addInteriorRing( ring.release() );
506 }
507 return polygon;
508}
509
510std::unique_ptr< QgsAbstractGeometry > parseGeometryFromGeoJson( const json &geometry )
511{
512 if ( !geometry.is_object() )
513 {
514 QgsDebugError( QStringLiteral( "JSON geometry value must be an object" ) );
515 return nullptr;
516 }
517
518 if ( !geometry.contains( "type" ) )
519 {
520 QgsDebugError( QStringLiteral( "JSON geometry must contain 'type'" ) );
521 return nullptr;
522 }
523
524 const QString type = QString::fromStdString( geometry["type"].get< std::string >() );
525 if ( type.compare( QLatin1String( "Point" ), Qt::CaseInsensitive ) == 0 )
526 {
527 if ( !geometry.contains( "coordinates" ) )
528 {
529 QgsDebugError( QStringLiteral( "JSON Point geometry must contain 'coordinates'" ) );
530 return nullptr;
531 }
532
533 const json &coords = geometry["coordinates"];
534 return parsePointFromGeoJson( coords );
535 }
536 else if ( type.compare( QLatin1String( "MultiPoint" ), Qt::CaseInsensitive ) == 0 )
537 {
538 if ( !geometry.contains( "coordinates" ) )
539 {
540 QgsDebugError( QStringLiteral( "JSON MultiPoint geometry must contain 'coordinates'" ) );
541 return nullptr;
542 }
543
544 const json &coords = geometry["coordinates"];
545
546 if ( !coords.is_array() )
547 {
548 QgsDebugError( QStringLiteral( "JSON MultiPoint geometry coordinates must be an array" ) );
549 return nullptr;
550 }
551
552 std::unique_ptr< QgsMultiPoint > multiPoint = std::make_unique< QgsMultiPoint >();
553 multiPoint->reserve( static_cast< int >( coords.size() ) );
554 for ( const auto &pointCoords : coords )
555 {
556 std::unique_ptr< QgsPoint > point = parsePointFromGeoJson( pointCoords );
557 if ( !point )
558 {
559 return nullptr;
560 }
561 multiPoint->addGeometry( point.release() );
562 }
563
564 return multiPoint;
565 }
566 else if ( type.compare( QLatin1String( "LineString" ), Qt::CaseInsensitive ) == 0 )
567 {
568 if ( !geometry.contains( "coordinates" ) )
569 {
570 QgsDebugError( QStringLiteral( "JSON LineString geometry must contain 'coordinates'" ) );
571 return nullptr;
572 }
573
574 const json &coords = geometry["coordinates"];
575 return parseLineStringFromGeoJson( coords );
576 }
577 else if ( type.compare( QLatin1String( "MultiLineString" ), Qt::CaseInsensitive ) == 0 )
578 {
579 if ( !geometry.contains( "coordinates" ) )
580 {
581 QgsDebugError( QStringLiteral( "JSON MultiLineString geometry must contain 'coordinates'" ) );
582 return nullptr;
583 }
584
585 const json &coords = geometry["coordinates"];
586
587 if ( !coords.is_array() )
588 {
589 QgsDebugError( QStringLiteral( "JSON MultiLineString geometry coordinates must be an array" ) );
590 return nullptr;
591 }
592
593 std::unique_ptr< QgsMultiLineString > multiLineString = std::make_unique< QgsMultiLineString >();
594 multiLineString->reserve( static_cast< int >( coords.size() ) );
595 for ( const auto &lineCoords : coords )
596 {
597 std::unique_ptr< QgsLineString > line = parseLineStringFromGeoJson( lineCoords );
598 if ( !line )
599 {
600 return nullptr;
601 }
602 multiLineString->addGeometry( line.release() );
603 }
604
605 return multiLineString;
606 }
607 else if ( type.compare( QLatin1String( "Polygon" ), Qt::CaseInsensitive ) == 0 )
608 {
609 if ( !geometry.contains( "coordinates" ) )
610 {
611 QgsDebugError( QStringLiteral( "JSON Polygon geometry must contain 'coordinates'" ) );
612 return nullptr;
613 }
614
615 const json &coords = geometry["coordinates"];
616 if ( !coords.is_array() || coords.size() < 1 )
617 {
618 QgsDebugError( QStringLiteral( "JSON Polygon geometry coordinates must be an array of at least one ring" ) );
619 return nullptr;
620 }
621
622 return parsePolygonFromGeoJson( coords );
623 }
624 else if ( type.compare( QLatin1String( "MultiPolygon" ), Qt::CaseInsensitive ) == 0 )
625 {
626 if ( !geometry.contains( "coordinates" ) )
627 {
628 QgsDebugError( QStringLiteral( "JSON MultiPolygon geometry must contain 'coordinates'" ) );
629 return nullptr;
630 }
631
632 const json &coords = geometry["coordinates"];
633
634 if ( !coords.is_array() )
635 {
636 QgsDebugError( QStringLiteral( "JSON MultiPolygon geometry coordinates must be an array" ) );
637 return nullptr;
638 }
639
640 std::unique_ptr< QgsMultiPolygon > multiPolygon = std::make_unique< QgsMultiPolygon >();
641 multiPolygon->reserve( static_cast< int >( coords.size() ) );
642 for ( const auto &polygonCoords : coords )
643 {
644 std::unique_ptr< QgsPolygon > polygon = parsePolygonFromGeoJson( polygonCoords );
645 if ( !polygon )
646 {
647 return nullptr;
648 }
649 multiPolygon->addGeometry( polygon.release() );
650 }
651
652 return multiPolygon;
653 }
654 else if ( type.compare( QLatin1String( "GeometryCollection" ), Qt::CaseInsensitive ) == 0 )
655 {
656 if ( !geometry.contains( "geometries" ) )
657 {
658 QgsDebugError( QStringLiteral( "JSON GeometryCollection geometry must contain 'geometries'" ) );
659 return nullptr;
660 }
661
662 const json &geometries = geometry["geometries"];
663
664 if ( !geometries.is_array() )
665 {
666 QgsDebugError( QStringLiteral( "JSON GeometryCollection geometries must be an array" ) );
667 return nullptr;
668 }
669
670 std::unique_ptr< QgsGeometryCollection > collection = std::make_unique< QgsGeometryCollection >();
671 collection->reserve( static_cast< int >( geometries.size() ) );
672 for ( const auto &geometry : geometries )
673 {
674 std::unique_ptr< QgsAbstractGeometry > object = parseGeometryFromGeoJson( geometry );
675 if ( !object )
676 {
677 return nullptr;
678 }
679 collection->addGeometry( object.release() );
680 }
681
682 return collection;
683 }
684
685 QgsDebugError( QStringLiteral( "Unhandled GeoJSON geometry type: %1" ).arg( type ) );
686 return nullptr;
687}
688
690{
691 if ( !geometry.is_object() )
692 {
693 QgsDebugError( QStringLiteral( "JSON geometry value must be an object" ) );
694 return QgsGeometry();
695 }
696
697 return QgsGeometry( parseGeometryFromGeoJson( geometry ) );
698}
699
701{
702 try
703 {
704 const auto jObj( json::parse( geometry.toStdString() ) );
705 return geometryFromGeoJson( jObj );
706 }
707 catch ( json::parse_error &ex )
708 {
709 QgsDebugError( QStringLiteral( "Cannot parse json (%1): %2" ).arg( geometry, ex.what() ) );
710 return QgsGeometry();
711 }
712}
713
714json QgsJsonUtils::jsonFromVariant( const QVariant &val )
715{
716 if ( QgsVariantUtils::isNull( val ) )
717 {
718 return nullptr;
719 }
720 json j;
721 if ( val.type() == QVariant::Type::Map )
722 {
723 const QVariantMap &vMap = val.toMap();
724 json jMap = json::object();
725 for ( auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
726 {
727 jMap[ it.key().toStdString() ] = jsonFromVariant( it.value() );
728 }
729 j = jMap;
730 }
731 else if ( val.type() == QVariant::Type::List || val.type() == QVariant::Type::StringList )
732 {
733 const QVariantList &vList = val.toList();
734 json jList = json::array();
735 for ( const auto &v : vList )
736 {
737 jList.push_back( jsonFromVariant( v ) );
738 }
739 j = jList;
740 }
741 else
742 {
743 switch ( val.userType() )
744 {
745 case QMetaType::Int:
746 case QMetaType::UInt:
747 case QMetaType::LongLong:
748 case QMetaType::ULongLong:
749 j = val.toLongLong();
750 break;
751 case QMetaType::Double:
752 case QMetaType::Float:
753 j = val.toDouble();
754 break;
755 case QMetaType::Bool:
756 j = val.toBool();
757 break;
758 case QMetaType::QByteArray:
759 j = val.toByteArray().toBase64().toStdString();
760 break;
761 default:
762 j = val.toString().toStdString();
763 break;
764 }
765 }
766 return j;
767}
768
769QVariant QgsJsonUtils::parseJson( const std::string &jsonString )
770{
771 QString error;
772 const QVariant res = parseJson( jsonString, error );
773
774 if ( !error.isEmpty() )
775 {
776 QgsLogger::warning( QStringLiteral( "Cannot parse json (%1): %2" ).arg( error,
777 QString::fromStdString( jsonString ) ) );
778 }
779 return res;
780}
781
782QVariant QgsJsonUtils::parseJson( const std::string &jsonString, QString &error )
783{
784 error.clear();
785 try
786 {
787 const json j = json::parse( jsonString );
788 return jsonToVariant( j );
789 }
790 catch ( json::parse_error &ex )
791 {
792 error = QString::fromStdString( ex.what() );
793 }
794 return QVariant();
795}
796
797QVariant QgsJsonUtils::jsonToVariant( const json &value )
798{
799 // tracks whether entire json string is a primitive
800 bool isPrimitive = true;
801
802 std::function<QVariant( json )> _parser { [ & ]( json jObj ) -> QVariant {
803 QVariant result;
804 if ( jObj.is_array() )
805 {
806 isPrimitive = false;
807 QVariantList results;
808 results.reserve( jObj.size() );
809 for ( const auto &item : jObj )
810 {
811 results.push_back( _parser( item ) );
812 }
813 result = results;
814 }
815 else if ( jObj.is_object() )
816 {
817 isPrimitive = false;
818 QVariantMap results;
819 for ( const auto &item : jObj.items() )
820 {
821 const auto key { QString::fromStdString( item.key() ) };
822 const auto value { _parser( item.value() ) };
823 results[ key ] = value;
824 }
825 result = results;
826 }
827 else
828 {
829 if ( jObj.is_number_unsigned() )
830 {
831 // Try signed int and long long first, fall back
832 // onto unsigned long long
833 const qulonglong num { jObj.get<qulonglong>() };
834 if ( num <= std::numeric_limits<int>::max() )
835 {
836 result = static_cast<int>( num );
837 }
838 else if ( num <= std::numeric_limits<qlonglong>::max() )
839 {
840 result = static_cast<qlonglong>( num );
841 }
842 else
843 {
844 result = num;
845 }
846 }
847 else if ( jObj.is_number_integer() )
848 {
849 const qlonglong num { jObj.get<qlonglong>() };
850 if ( num <= std::numeric_limits<int>::max() && num >= std::numeric_limits<int>::lowest() )
851 {
852 result = static_cast<int>( num );
853 }
854 else
855 {
856 result = num;
857 }
858 }
859 else if ( jObj.is_boolean() )
860 {
861 result = jObj.get<bool>();
862 }
863 else if ( jObj.is_number_float() )
864 {
865 // Note: it's a double and not a float on purpose
866 result = jObj.get<double>();
867 }
868 else if ( jObj.is_string() )
869 {
870 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
871 {
872 result = QString::fromStdString( jObj.get<std::string>() ).append( "\"" ).insert( 0, "\"" );
873 }
874 else
875 {
876 result = QString::fromStdString( jObj.get<std::string>() );
877 }
878 }
879 else if ( jObj.is_null() )
880 {
881 // Do nothing (leave invalid)
882 }
883 }
884 return result;
885 }
886 };
887
888 return _parser( value );
889}
890
891QVariant QgsJsonUtils::parseJson( const QString &jsonString )
892{
893 return parseJson( jsonString.toStdString() );
894}
895
896json QgsJsonUtils::exportAttributesToJsonObject( const QgsFeature &feature, QgsVectorLayer *layer, const QVector<QVariant> &attributeWidgetCaches )
897{
898 QgsFields fields = feature.fields();
899 json attrs;
900 for ( int i = 0; i < fields.count(); ++i )
901 {
902 QVariant val = feature.attributes().at( i );
903
904 if ( layer )
905 {
906 QgsEditorWidgetSetup setup = layer->fields().at( i ).editorWidgetSetup();
908 if ( fieldFormatter != QgsApplication::fieldFormatterRegistry()->fallbackFieldFormatter() )
909 val = fieldFormatter->representValue( layer, i, setup.config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
910 }
911 attrs[fields.at( i ).name().toStdString()] = jsonFromVariant( val );
912 }
913 return attrs;
914}
@ Success
Operation succeeded.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source coordinate reference system.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination coordinate reference system.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:67
Holder for the widget type and its configuration for a field.
QVariantMap config() const
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsAttributes attributes
Definition: qgsfeature.h:65
QgsFields fields
Definition: qgsfeature.h:66
QgsGeometry geometry
Definition: qgsfeature.h:67
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
QgsFieldFormatter * fieldFormatter(const QString &id) const
Gets a field formatter by its id.
A field formatter helps to handle and display values for a field.
virtual QVariant createCache(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config) const
Create a cache for a given field.
virtual QString id() const =0
Returns a unique id for this field formatter.
virtual QString representValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const
Create a pretty String representation of the value.
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:53
QString name
Definition: qgsfield.h:62
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
Definition: qgsfield.cpp:714
Container of fields for a vector layer.
Definition: qgsfields.h:45
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Definition: qgsfields.cpp:163
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Q_GADGET bool isNull
Definition: qgsgeometry.h:164
virtual json asJsonObject(int precision=17) const
Exports the geometry to a json object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
json exportFeatureToJsonObject(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a QJsonObject representation of a feature.
json exportFeaturesToJsonObject(const QgsFeatureList &features) const
Returns a JSON object representation of a list of features (feature collection).
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
void setDestinationCrs(const QgsCoordinateReferenceSystem &destinationCrs)
Set the destination CRS for feature geometry transformation to destinationCrs, this defaults to EPSG:...
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant(), int indent=-1) const
Returns a GeoJSON string representation of a feature.
QString exportFeatures(const QgsFeatureList &features, int indent=-1) const
Returns a GeoJSON string representation of a list of features (feature collection).
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
static QgsGeometry geometryFromGeoJson(const json &geometry)
Parses a GeoJSON "geometry" value to a QgsGeometry object.
static QString exportAttributes(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a JSON map type.
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields=QgsFields(), QTextCodec *encoding SIP_PYARGREMOVE6=nullptr)
Attempts to parse a GeoJSON string to a collection of features.
static Q_INVOKABLE QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
static json exportAttributesToJsonObject(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a json object.
static Q_INVOKABLE QVariantList parseArray(const QString &json, QVariant::Type type=QVariant::Invalid)
Parse a simple array (depth=1)
static QVariant jsonToVariant(const json &value)
Converts a JSON value to a QVariant, in case of parsing error an invalid QVariant is returned.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding SIP_PYARGREMOVE6=nullptr)
Attempts to retrieve the fields from a GeoJSON string representing a collection of features.
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
static void warning(const QString &msg)
Goes to qWarning.
Definition: qgslogger.cpp:131
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:81
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR.
QgsRelationManager * relationManager
Definition: qgsproject.h:117
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:481
A rectangle specified with double values.
Definition: qgsrectangle.h:42
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:201
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:211
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:196
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:206
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:628
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
Definition: qgis.h:5248
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:917
#define FID_IS_NULL(fid)
Definition: qgsfeatureid.h:30
std::unique_ptr< QgsPoint > parsePointFromGeoJson(const json &coords)
std::unique_ptr< QgsPolygon > parsePolygonFromGeoJson(const json &coords)
std::unique_ptr< QgsAbstractGeometry > parseGeometryFromGeoJson(const json &geometry)
std::unique_ptr< QgsLineString > parseLineStringFromGeoJson(const json &coords)
#define QgsDebugError(str)
Definition: qgslogger.h:38
QgsSQLStatement::Node * parse(const QString &str, QString &parserErrorMsg, bool allowFragments)
const QgsCoordinateReferenceSystem & crs
int precision