[GIS] Is it possible to export a GeoJSON with an array field from a joined layer

arraygeojsonqgis

I'm using QGIS to 1) load a shapefile, 2) join the shapefile data with a CSV-file and finally 3) exporting the layer as GeoJSON. Hence, I end up with something like this, where the properties object contains the original CSV data.

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
         "type": "Point",
         "coordinates": [102.0, 0.5]
       },
      "properties": {
         "prop0": "value0",
         "prop1": "value1",
         "prop2": "value2"
      }
    },...

What I really want to do is to store some of the properties in an array, as such:

"properties": {
    "prop0": "value0",
    "arr": [
        "value1",
        "value2"
]

Is it possible to export GeoJSON in such a format using QGIS? If not, does anyone have any other ideas as to how to edit GeoJSON data like that?

Best Answer

Looks like you'll need to serialize and write your own GeoJSON data structure. The Python QGIS bindings will give you access to individual features. Loop over all features in your layer and convert them to Python dicts (which share syntax with JSON, very handy) with the array property you're looking for. Then use Python's standard json lib to write them. Something like this:

features = []
for q_feature in q_layer:
    f = {
        'id': ..., 
        'type': 'Feature', 
        'geometry': ..., 
        'properties': {'arr': [...]}}
    features.append(f)

collection = {'type': 'FeatureCollection', 'features': features}
json.dump(collection, open('output.json', w'))

Replace the ellipses with your own values.

Related Question