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