Working with JSON data in a QGIS processing model

Working with (non-geo) JSON data in a QGIS model is not as easy as it should be, but it is still possible. In a previous post, Python was used to process JSON data and make it available for further processing in a model. This time, I wanted to include downloading the data as well.

Visit Sweden has published a data set with tourist destinations in Sweden. Using a combination of Python and a processing model, it´s possible to download the data set, extract the desired parts and output the result to the QGIS canvas.

As always, create the script separately, save it and then drop it into the model. The simple model looks like this:

After downloading the data, the model removes a few features with missing or incorrect coordinates.

Like most data sets, it does come with a few data quality slip-ups, such as:

  • Missing data:
  • Incorrect data: Coordinates set to unrealistic values
  • Inconsistent data: Country set to Sweden/sweden/null

Having algorithms for dealing with JSON data directly in the model would make this process easier, skipping the Pyhton part. If you want to try the current solution, here is the Python code:

from qgis.core import QgsProcessing, QgsProcessingAlgorithm, QgsProcessingOutputVectorLayer, QgsVectorLayer, QgsFeature, QgsGeometry, QgsField, QgsFields, QgsWkbTypes
from qgis.PyQt.QtCore import QVariant
import requests
import json

class FetchVisitSwedenData(QgsProcessingAlgorithm):
    OUTPUT = 'OUTPUT'
    
    def initAlgorithm(self, config=None):
        self.addOutput(QgsProcessingOutputVectorLayer(self.OUTPUT, 'Visit Sweden Places'))
    
    def processAlgorithm(self, parameters, context, feedback):
        # Fix SSL certificate issue
        import os
        
        # Try to use certifi if available
        try:
            import certifi
            os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
            feedback.pushInfo(f"Using certifi SSL certificates: {certifi.where()}")
        except ImportError:
            # If certifi is not available, disable SSL verification as fallback
            feedback.pushWarning("certifi not found, will disable SSL verification")
            import urllib3
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        
        # API URL
        url = "https://data.visitsweden.com/store/search"
        
        # Create fields for the layer
        fields = QgsFields()
        fields.append(QgsField('id', QVariant.String))
        fields.append(QgsField('namn', QVariant.String))
        fields.append(QgsField('typ', QVariant.String))
        fields.append(QgsField('beskrivning', QVariant.String))
        fields.append(QgsField('url', QVariant.String))
        fields.append(QgsField('ort', QVariant.String))
        fields.append(QgsField('land', QVariant.String))
        fields.append(QgsField('latitude', QVariant.Double))
        fields.append(QgsField('longitude', QVariant.Double))
        
        # Create temporary vector layer without geometry
        layer = QgsVectorLayer("None", "visit_sweden_data", "memory")
        provider = layer.dataProvider()
        provider.addAttributes(fields)
        layer.updateFields()
        
        # Fetch all records with pagination
        offset = 0
        limit = 100  # Fetch 100 records at a time
        total_features = 0
        features_with_coords = 0
        features_without_coords = 0
        
        feedback.pushInfo("Starting to fetch all records from Visit Sweden API...")
        
        while True:
            params = {
                'type': 'solr',
                'query': 'public:true AND (rdfType:http\\://schema.org/FoodEstablishment OR rdfType:http\\://schema.org/Event OR rdfType:http\\://schema.org/Place OR rdfType:http\\://schema.org/Store OR rdfType:http\\://schema.org/LodgingBusiness OR rdfType:http\\://schema.org/Trip)',
                'limit': limit,
                'offset': offset,
                'rdfFormat': 'application/ld+json'
            }
            
            feedback.pushInfo(f"Fetching records {offset} to {offset + limit}...")
            
            try:
                response = requests.get(url, params=params, verify=certifi.where() if 'certifi' in dir() else False)
                response.raise_for_status()
                data = response.json()
            except Exception as e:
                feedback.reportError(f"Error fetching data: {str(e)}")
                break
            
            # Check if we have more records
            if 'resource' not in data or 'children' not in data['resource']:
                feedback.pushInfo("No more records to fetch.")
                break
            
            children = data['resource']['children']
            
            if len(children) == 0:
                feedback.pushInfo("No more records to fetch.")
                break
            
            # Process each record
            features_in_batch = 0
            for child in children:
                feature = QgsFeature()
                feature.setFields(fields)
                
                try:
                    metadata = child.get('metadata', {})
                    graph = metadata.get('@graph', [{}])[0]
                    
                    # Extract data
                    feature['id'] = graph.get('dcterms:identifier', '')
                    
                    # Handle name
                    namn = graph.get('schema:name', {})
                    if isinstance(namn, dict):
                        feature['namn'] = namn.get('@value', '')
                    else:
                        feature['namn'] = str(namn) if namn else ''
                    
                    # Type
                    typ = graph.get('@type', '')
                    feature['typ'] = typ.replace('schema:', '') if typ else ''
                    
                    # Description (abstract or description)
                    beskrivning = graph.get('dcterms:abstract', graph.get('schema:description', {}))
                    if isinstance(beskrivning, dict):
                        feature['beskrivning'] = beskrivning.get('@value', '')
                    else:
                        feature['beskrivning'] = str(beskrivning) if beskrivning else ''
                    
                    # URL
                    url_obj = graph.get('schema:url', {})
                    if isinstance(url_obj, dict):
                        feature['url'] = url_obj.get('@id', '')
                    else:
                        feature['url'] = str(url_obj) if url_obj else ''
                    
                    # Search for address and coordinates in all objects in @graph
                    address = None
                    geo_coords = None
                    
                    for item in metadata.get('@graph', []):
                        if item.get('@type') == 'schema:PostalAddress':
                            address = item
                        elif item.get('@type') == 'schema:GeoCoordinates':
                            geo_coords = item
                    
                    # Handle address
                    if address:
                        ort = address.get('schema:addressLocality', {})
                        if isinstance(ort, dict):
                            feature['ort'] = ort.get('@value', '')
                        else:
                            feature['ort'] = str(ort) if ort else ''
                        
                        feature['land'] = address.get('schema:addressCountry', '')
                    
                    # Handle coordinates - only save the values
                    if geo_coords:
                        try:
                            lat = float(geo_coords.get('schema:latitude', ''))
                            lon = float(geo_coords.get('schema:longitude', ''))
                            
                            feature['latitude'] = lat
                            feature['longitude'] = lon
                            features_with_coords += 1
                        except (ValueError, TypeError):
                            features_without_coords += 1
                    else:
                        features_without_coords += 1
                    
                    provider.addFeature(feature)
                    features_in_batch += 1
                    total_features += 1
                    
                except Exception as e:
                    feedback.pushInfo(f"Could not process record: {str(e)}")
                    continue
            
            feedback.pushInfo(f"Processed {features_in_batch} records. Total: {total_features}")
            
            # If we got fewer than limit records, we're done
            if len(children) < limit:
                feedback.pushInfo("All records fetched.")
                break
            
            # Increase offset for next round
            offset += limit
        
        layer.updateExtents()
        feedback.pushInfo(f"=== COMPLETE! ===")
        feedback.pushInfo(f"Total {total_features} records loaded")
        feedback.pushInfo(f"With coordinates: {features_with_coords}")
        feedback.pushInfo(f"Without coordinates: {features_without_coords}")
        
        # Add the layer to the project
        context.project().addMapLayer(layer)
        
        return {self.OUTPUT: layer.id()}
    
    def name(self):
        return 'fetch_visitsweden'
    
    def displayName(self):
        return 'Fetch Visit Sweden Data (All Records)'
    
    def group(self):
        return 'Data Import'
    
    def groupId(self):
        return 'dataimport'
    
    def createInstance(self):
        return FetchVisitSwedenData()

This was done with some guidance from Claude.ai and works in QGIS 3.44.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait