def testExportAttributes(self): """ test exporting feature's attributes to JSON object """ fields = QgsFields() # test empty attributes feature = QgsFeature(fields, 5) expected = "{}" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected) # test feature with attributes fields.append(QgsField("name", QVariant.String)) fields.append(QgsField("cost", QVariant.Double)) fields.append(QgsField("population", QVariant.Int)) feature = QgsFeature(fields, 5) feature.setGeometry(QgsGeometry(QgsPointV2(5, 6))) feature.setAttributes(['Valsier Peninsula', 6.8, 198]) expected = """{"name":"Valsier Peninsula", "cost":6.8, "population":198}""" self.assertEqual(QgsJSONUtils.exportAttributes(feature), expected)
fields_list = [ QgsField("name", QVariant.String), QgsField("age", QVariant.Int), QgsField("size", QVariant.Double) ] for f in fields_list: fields.append(f) feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(60, 5))) feature.setAttributes(["George", 34, 1.69]) # Exports all attributes from a QgsFeature as a JSON map type. with codecs.open('feature.json', 'wb', encoding='utf-8') as f: json_text = QgsJSONUtils.exportAttributes(feature) f.write(json_text) # Attempts to retrieve the fields from a GeoJSON string representing a # collection of features. fields = QgsJSONUtils.stringToFields( geojson_contributors_string, QTextCodec.codecForName('UTF-8') ) for f in fields: print(f.name(), f.type()) # Attempts to parse a GeoJSON string to a collection of features. features = QgsJSONUtils.stringToFeatureList( geojson_contributors_string,