'How to convert JSON to GeoJSON with Python

I'm actually learning how to do some cartography with python but first I would like to convert my json file to a GeoJson dynamically with Python. This is how my Json looks like :

[
  {
    "shape_name": "unit_shape",
    "source_name": "7724C_BUSSY_SAINT_GEORGES_Bussycomore",
    "building_id": "7724C",
    "chaud_froid": "Chaud",
    "geojson": {
      "type": "LineString",
      "properties": {
        "densite_cc": null
      },
      "coordinates": [
        [
          2.726142,
          48.834359
        ],
        [
          2.726149,
          48.834367
        ],
        [
          2.726202,
          48.834422
        ],
        [
          2.726262,
          48.834429
        ],
        [
          2.726307,
          48.834434
        ],
        [
          2.726316,
          48.834435
        ]
      ]
    },
    "to_drop": null,
    "id_enquete": null,
    "shape_nom": null
  },
...(many other features similar to the precedent one)]

Can someone please help me ?



Solution 1:[1]

import json 

input_file=json.load(open("./data/data.json", "r", encoding="utf-8"))

geojs={
     "type": "FeatureCollection",
     "features":[
           {
                "type":"Feature",
                "geometry": {
                "type":"LineString",
                "coordinates":d["geojson"]["coordinates"],
            },
                "properties":d,
        
         } for d in input_file 
    ]  
 }

output_file=open("./data/geodata.json", "w", encoding="utf-8")
json.dump(geojs, output_file)


output_file.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sig21