将JSON转换为QGIS GeoJSON:同时具有多种功能和不同的类型 [英] Converting JSON to QGIS GeoJSON: while having multiple features and different types

查看:143
本文介绍了将JSON转换为QGIS GeoJSON:同时具有多种功能和不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个程序可以从特定的API请求JSONS.API的创建者声称此数据位于GeoJSON中,但QGIS无法读取.

因此,我想扩展我的Python脚本,将JSON以可读的格式转换为GEOJSON,以进入QGIS并在那里进行进一步处理.

但是,我有一些问题,我不知道从哪里开始以及JSON文件是如何构造的……这真是一团糟.JSONS实际上是基于两个API Get Request制成的.一个Api Get Request请求积分,第二个Api Get Request请求积分的详细信息.有关更多上下文,请参见此处的问题:另一个API请求Python中的API请求(相同的API)

请注意,由于字符限制,我无法在此处发布代码:

这些细节当然应该被认为是轮廓".这些点周围的区域.问题是..点本身在JSON中被提及,这使得很难指定每个点的坐标.更不用说对我们来说有趣的所有其他属性都在点"中.的一部分.

看看JSON本身,了解我的意思:

  {评论":null,"contactDetails":{"city":null,国家":"BE",电子邮件":null,"extraAddressInfo":null,"firstName":null,"kboNumber":null,"lastname":"TMVW",数字":null,组织":"TMVW-Brugge-Kust","phoneNumber1":null,"phoneNumber2":null,"postalCode":null,街道":空},承包商":null,说明":"WEGENISWERKEN-Oostende-154-W-H Baelskaai-project Oosteroever",转移":[],"endDateTime":"2021-06-30T00:00:00","gipodId":1042078,阻碍":{说明":null,"direction":null,效果":["Omleiding:beide richtingen","Afgesloten:volledige rijweg","Fietsers hebben geen doorgang","Handelaars bereikbaar","Plaatselijk verkeer:toegelaten","Voetgangers hebben doorgang";],重要":是的,位置":[语音垫","Fietspad","Parkeerstrook","Rijbaan"]},"latestUpdate":"2020-12-01T12:16:00.03",位置":{城市":[奥斯坦德"],坐标":{坐标":[2.931988215468502,51.23633810341717],"crs":{属性":{名称":"urn:ogc:def:crs:OGC:1.3:CRS84"},类型":名称"},类型":点"},"geometry":{坐标":[[[2.932567101705748,51.23657315009855],[2.9309934586397337,51.235776874431004],[2.9328606392338914,51.2345112414401],[2.9344086040607285,51.23535468563417],[2.9344709862243095,51.23529463700852],[2.932928489694045,51.23447026126373],[2.935453674897618,51.2326691257775],[2.937014893295095,51.23347469462423],[2.9370649363167556,51.23342209549579],[2.9355339718818847,51.23261689467634],[2.937705787093551,51.23108125372614],[2.939235922008332,51.23191301940206],[2.9393162149112086,51.231860784836144],[2.9377921292631313,51.23102909334536],[2.9395494398210404,51.22978103014327],[2.9395326861153492,51.22973522407282],[2.9307116955342982,51.23588365892173],[2.93077732400986,51.235914858980586],[2.930921969180147,51.23581685905391],[2.932475593354336,51.23662429379119],[2.932567101705748,51.23657315009855]]],"crs":{属性":{名称":"urn:ogc:def:crs:OGC:1.3:CRS84"},"type":"name"},"type":"Polygon"}},"mainContractor":null,所有者":"TMVW-Brugge-Kust",参考":"DOM-154/15/004-W","startDateTime":"2017-05-02T00:00:00",状态":因果关系",类型":"Wegeniswerken(her)aanleg","URL":空} 

提醒一下,这些JSON不应视为点文件,并且几何形状可以是如上所示的多边形:multipolygon或multiLinestring(此处没有示例).

那我应该如何开始并确保不仅获得细节属性,而且要清楚轮廓几何形状和坐标?

唯一的唯一ID是GIPOD ID,因为该ID是该API数据库中实际链接的位置.

这就是所谓的geojson标准.

  {"type":"Feature","geometry":{"type":"Point",坐标":[125.6,10.1]},属性":{名称":"Dinagat Islands"}} 

基于此标准,转换后的JSON应该是这样的:

 "type":"Feature","geometry":{类型":多边形",坐标":[[[2.932567101705748,51.23657315009855],[2.9309934586397337,51.235776874431004],[2.9328606392338914,51.2345112414401],[2.9344086040607285,51.23535468563417],[2.9344709862243095,51.23529463700852],[2.932928489694045,51.23447026126373],[2.935453674897618,51.2326691257775],[2.937014893295095,51.23347469462423],[2.9370649363167556,51.23342209549579],[2.9355339718818847,51.23261689467634],[2.937705787093551,51.23108125372614],[2.939235922008332,51.23191301940206],[2.9393162149112086,51.231860784836144],[2.9377921292631313,51.23102909334536],[2.9395494398210404,51.22978103014327],[2.9395326861153492,51.22973522407282],[2.9307116955342982,51.23588365892173],[2.93077732400986,51.235914858980586],[2.930921969180147,51.23581685905391],[2.932475593354336,51.23662429379119],[2.932567101705748,51.23657315009855]]},属性":{列数过多,由于字符数限制,无法在此处声明所有列.}} 

提供的解决方案是朝正确方向迈出的良好一步,但它给了我两个问题:

  1. 保存的几何为Null,使此JSON成为没有表的表几何.
  2. 仅保存1个data_point,而不是所有的data_point被要求.

这是JSON:

  {"type":"FeatureCollection","features":[{"type":"Feature","geometry":null,"properties":{"gipodId";:3099549,"StartDateTime":null,"EndDateTime":null,"state":null,"location":{"citys":["Waregem","Wielsbeke"],坐标":{坐标":[3.4206971887218445,50.91662742195287],类型":点","crs":{类型":名称",属性":{名称";:" urn:ogc:def:crs:OGC:1.3:CRS84"}}}}}}}]}} 

Python代码:下面看它走了多远:

 导入请求导入json导入操作系统导入球进口壁垒def process_location_data(location_json):"将数据点转换为所需的geojson格式.#分配变量以存储几何详细信息geometery_details = location_json.get("location").get("geometery")#geometery_details.pop("crs")#删除"crs"从几何#包括城市和location_coordinateslocation_details = {"city":location_json.get("location").get("city"),坐标":location_json.get(位置").get(坐标")}#EndDateTimeend_datetime = location_json.get("EndDateTime")#StarDateTimestart_datetime = location_json.get("StarDateTime")#状态状态= location_json.get(状态")#gipodIdgipod_id = location_json.get(" gipodId")#将所有这些详细信息添加到另一个字典中属性= {"gipodId":gipod_id,"StartDateTime":start_datetime,"EndDateTime":end_datetime,状态":状态,"location":location_details}#创建要返回的最终字典.geojson_data_point = {"type":"Feature",几何":geometery_details,"properties":属性}返回geojson_data_pointdef process_all_location_data(all_location_points):"对于位置详细信息中的所有点,我们将创建要素集合"feature_collection = {"type":"FeatureCollection",功能":[]}#创建零要素的字典.对于all_location_points中的data_point:feature_collection.get(功能").append(process_location_data(data_point))返回feature_collectiondef fetch_details(URL:str,file_name:str):#进行请求调用以获取详细数据响应= requests.get(URL)打印(发送有关gpodId的详细信息的请求:"+ file_name)folder_path ='api_request_jsons/fetch_details/JSON未过滤'文字= json.dumps(response.json(),sort_keys = False,indent = 4)print("提取的详细信息:" + file_name)保存文件(文件夹路径,文件名,文本)返回response.json()#save_file(folder_path,GipodId,text2)#其他任何进程def fetch_points(url:str):响应= requests.get(URL)folder_path ='api_request_jsons/fetch_points'text = json.dumps(response.json(),sort_keys = False,indent = 4)打印(已获取积分,进入下一步:提取详细信息")对于response.json()中的obj:all_location_points = [fetch_details(obj.get("detail"),, str(obj.get("gipodId"))))]save_file(folder_path,'points',text)feature_collection_json = process_all_location_data(all_location_points)text2 = json.dumps(process_all_location_data(all_location_points))folder_path2 =" api_request_jsons/fetch_details/Coordinates"file_name2 =已转换";save_file(文件夹路径2,文件名2,文本2)返回feature_collection_jsondef save_file(save_path:str,file_name:str,file_information:str):completeName = os.path.join(save_path,file_name +.json")打印(completeName +已保存")file1 =打开(completeName,"wt")file1.write(文件信息)file1.close()api_response_url ="http://api.gipod.vlaanderen.be/ws/v1/workassignment"fetch_points(api_response_url) 

解决方案

基于问题的#Edit 3,我已经更新了完整的解决方案.有两个问题.

  • 函数 process_location_data 中的错字.在此功能中,我正在加载 geometryy 而不是 geometry (请检查拼写中的拼写错误)

 #代码错误geometery_details = location_json.get("location").get("geometery")#正确的一个geometery_details = location_json.get("location").get("geometry") 

此外,我在对象的 state endDateTime startDateTime 键中发现了错别字.(已在下面提供的完整解决方案中修复)

  • fetch_points 函数中添加列表 all_location_points .

 #当前代码对于response.json()中的obj:all_location_points = [fetch_details(obj.get("detail"),str(obj.get("gipodId"))))] 

在这个 all_location_points 中,每次使用 obj 进行更新,而不是将其附加到列表中.

 #固定的all_location_points = []对于response.json()中的obj:all_location_points.append(fetch_details(obj.get("detail"),str(obj.get("gipodId"))))) 

在上面的答案中,我曾用速记来创建列表(列表理解).以上3行可以转换为单行为

  all_location_points = [fetch_details(obj.get("detail"),str(obj.get("gipodId"))))用于response.json()中的obj] 

完整的更新解决方案,(包括拼写错误和附加列表)

 汇入要求导入json导入操作系统导入球进口壁垒def process_location_data(location_json):"将数据点转换为所需的geojson格式.#分配变量以存储几何详细信息geometery_details = location_json.get("location").get("geometry")#geometery_details.pop("crs")#删除"crs"从几何#包括城市和location_coordinateslocation_details = {"city":location_json.get("location").get("city"),坐标":location_json.get("location").get("coordinate"),}#EndDateTimeend_datetime = location_json.get(" endDateTime")#StarDateTimestart_datetime = location_json.get("startDateTime")# 状态状态= location_json.get(状态")#gipodIdgipod_id = location_json.get(" gipodId")#将所有这些详细信息添加到另一个字典中属性= {"gipodId":gipod_id,"StartDateTime":start_datetime,"EndDateTime":end_datetime,状态":状态,"location":location_details,}#创建要返回的最终字典.geojson_data_point = {"type":"Feature","geometry":geometery_details,"properties":属性,}返回geojson_data_pointdef process_all_location_data(all_location_points):"对于位置详细信息中的所有点,我们将创建要素集合"feature_collection = {"type":"FeatureCollection",功能":[],}#创建零特征的字典.对于all_location_points中的data_point:feature_collection.get(功能").append(process_location_data(data_point))返回feature_collectiondef fetch_details(URL:str,file_name:str):#进行请求调用以获取详细数据响应= requests.get(URL)打印(发送有关gpodId的详细信息的请求:"+ file_name)folder_path ="api_request_jsons/fetch_details/JSON未过滤"文字= json.dumps(response.json(),sort_keys = False,indent = 4)print("提取的详细信息:" + file_name)save_file(文件夹路径,文件名,文本)返回response.json()#save_file(folder_path,GipodId,text2)#其他任何进程def fetch_points(url:str):响应= requests.get(URL)folder_path ="api_request_jsons/fetch_points"文字= json.dumps(response.json(),sort_keys = False,indent = 4)打印(已获取积分,进入下一步:提取详细信息")all_location_points = []对于response.json()中的obj:all_location_points.append(fetch_details(obj.get("detail"),str(obj.get("gipodId")))))save_file(文件夹路径,点",文本)feature_collection_json = process_all_location_data(all_location_points)text2 = json.dumps(process_all_location_data(all_location_points))folder_path2 =" api_request_jsons/fetch_details/Coordinates"file_name2 =已转换";save_file(folder_path2,file_name2,text2)返回feature_collection_jsondef save_file(save_path:str,file_name:str,file_information:str):completeName = os.path.join(save_path,file_name +".json")打印(completeName +已保存")file1 =打开(completeName,"wt")file1.write(文件信息)file1.close()api_response_url ="http://api.gipod.vlaanderen.be/ws/v1/workassignment"fetch_points(api_response_url) 

Currently I have a program that request JSONS from specific API. The creators of the API have claimed this data is in GeoJSON but QGIS cannot read it.

So I want to extend my Python Script to converting the JSON to GEOJSON in a readable format to get into QGIS and process it further there.

However, I have a few problems, one I do not know where to start and How the JSON files are constructed...its kind of mess. The JSONS were actually maded based on two API Get Request. One Api Get Request request the Points and the second one requests the details of the points. See this question here for some more context: API Request within another API request (Same API) in Python

Note because of character limit I cannot post the code here:

These details are of course supposed to be "the contours" of the area surrounding these points. The thing is..the point itself is mentioned in the JSON, making it kind of hard to specify what coordinate is for each point. Not to mention all other attributes that are intresting to us, are in the "point" part of the GeoJSON.

Take a look at the JSON itself to see what I mean:

{
    "comment": null,
    "contactDetails": {
        "city": null,
        "country": "BE",
        "email": null,
        "extraAddressInfo": null,
        "firstName": null,
        "kboNumber": null,
        "lastName": "TMVW",
        "number": null,
        "organisation": "TMVW - Brugge-Kust",
        "phoneNumber1": null,
        "phoneNumber2": null,
        "postalCode": null,
        "street": null
    },
    "contractor": null,
    "description": "WEGENISWERKEN - Oostende - 154-W - H Baelskaai-project Oosteroever",
    "diversions": [],
    "endDateTime": "2021-06-30T00:00:00",
    "gipodId": 1042078,
    "hindrance": {
        "description": null,
        "direction": null,
        "effects": [
            "Omleiding: beide richtingen",
            "Afgesloten: volledige rijweg",
            "Fietsers hebben geen doorgang",
            "Handelaars bereikbaar",
            "Plaatselijk verkeer: toegelaten",
            "Voetgangers hebben doorgang"
        ],
        "important": true,
        "locations": [
            "Voetpad",
            "Fietspad",
            "Parkeerstrook",
            "Rijbaan"
        ]
    },
    "latestUpdate": "2020-12-01T12:16:00.03",
    "location": {
        "cities": [
            "Oostende"
        ],
        "coordinate": {
            "coordinates": [
                2.931988215468502,
                51.23633810341717
            ],
            "crs": {
                "properties": {
                    "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
                },
                "type": "name"
            },
            "type": "Point"
        },
        "geometry": {
            "coordinates": [
                [
                    [
                        2.932567101705748,
                        51.23657315009855
                    ],
                    [
                        2.9309934586397337,
                        51.235776874431004
                    ],
                    [
                        2.9328606392338914,
                        51.2345112414401
                    ],
                    [
                        2.9344086040607285,
                        51.23535468563417
                    ],
                    [
                        2.9344709862243095,
                        51.23529463700852
                    ],
                    [
                        2.932928489694045,
                        51.23447026126373
                    ],
                    [
                        2.935453674897618,
                        51.2326691257775
                    ],
                    [
                        2.937014893295095,
                        51.23347469462423
                    ],
                    [
                        2.9370649363167556,
                        51.23342209549579
                    ],
                    [
                        2.9355339718818847,
                        51.23261689467634
                    ],
                    [
                        2.937705787093551,
                        51.23108125372614
                    ],
                    [
                        2.939235922008332,
                        51.23191301940206
                    ],
                    [
                        2.9393162149112086,
                        51.231860784836144
                    ],
                    [
                        2.9377921292631313,
                        51.23102909334536
                    ],
                    [
                        2.9395494398210404,
                        51.22978103014327
                    ],
                    [
                        2.9395326861153492,
                        51.22973522407282
                    ],
                    [
                        2.9307116955342982,
                        51.23588365892173
                    ],
                    [
                        2.93077732400986,
                        51.235914858980586
                    ],
                    [
                        2.930921969180147,
                        51.23581685905391
                    ],
                    [
                        2.932475593354336,
                        51.23662429379119
                    ],
                    [
                        2.932567101705748,
                        51.23657315009855
                    ]
                ]
            ],
            "crs": {
                "properties": {
                    "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
                },
                "type": "name"
            },
            "type": "Polygon"
        }
    },
    "mainContractor": null,
    "owner": "TMVW - Brugge-Kust",
    "reference": "DOM-154/15/004-W",
    "startDateTime": "2017-05-02T00:00:00",
    "state": "In uitvoering",
    "type": "Wegeniswerken (her)aanleg",
    "url": null
}

As a reminder these JSON's are not supposed to be point files and the geometry can be either a polygon as seen above: A multipolygon or a multiLinestring (do not have an example here).

So how do I get started and make sure I not only get the detail attributes out but clearly the contour geometry and coordinates?

The only Unique id is the GIPOD ID, because this one is where the actual link in this API database is.

Edit 1:

So this is the supposed geojson standard.

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  },
  "properties": {
    "name": "Dinagat Islands"
  }
}

Based on this standard, the converted JSON should be this:

    "type": "Feature",
               "geometry": {
                   "type": "Polygon",
                   "coordinates": [
                    [
                        [
                            2.932567101705748,
                            51.23657315009855
                        ],
                        [
                            2.9309934586397337,
                            51.235776874431004
                        ],
                        [
                            2.9328606392338914,
                            51.2345112414401
                        ],
                        [
                            2.9344086040607285,
                            51.23535468563417
                        ],
                        [
                            2.9344709862243095,
                            51.23529463700852
                        ],
                        [
                            2.932928489694045,
                            51.23447026126373
                        ],
                        [
                            2.935453674897618,
                            51.2326691257775
                        ],
                        [
                            2.937014893295095,
                            51.23347469462423
                        ],
                        [
                            2.9370649363167556,
                            51.23342209549579
                        ],
                        [
                            2.9355339718818847,
                            51.23261689467634
                        ],
                        [
                            2.937705787093551,
                            51.23108125372614
                        ],
                        [
                            2.939235922008332,
                            51.23191301940206
                        ],
                        [
                            2.9393162149112086,
                            51.231860784836144
                        ],
                        [
                            2.9377921292631313,
                            51.23102909334536
                        ],
                        [
                            2.9395494398210404,
                            51.22978103014327
                        ],
                        [
                            2.9395326861153492,
                            51.22973522407282
                        ],
                        [
                            2.9307116955342982,
                            51.23588365892173
                        ],
                        [
                            2.93077732400986,
                            51.235914858980586
                        ],
                        [
                            2.930921969180147,
                            51.23581685905391
                        ],
                        [
                            2.932475593354336,
                            51.23662429379119
                        ],
                        [
                            2.932567101705748,
                            51.23657315009855
                        ]
                   ]
               },
               "properties": {
Too much columns to type, cannot claim them all here because of character limit.
                   }
           }

Edit 3: The Solution provided was a good step in the right direction but it gives me two problems:

  1. The saved geometry is Null making this JSON a table without geometry.
  2. Only 1 data_point is saved and not all data_points that are being requested.

Here is the JSON:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": null, "properties": {"gipodId": 3099549, "StartDateTime": null, "EndDateTime": null, "state": null, "location": {"cities": ["Waregem", "Wielsbeke"], "coordinate": {"coordinates": [3.4206971887218445, 50.91662742195287], "type": "Point", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}}}}}]}

Python Code: Below to see how far it has gone:

import requests
import json
import os
import glob
import shutil

def process_location_data(location_json): 
   """Converts the data point into required geojson format"""

  
   # assigning variable to store geometry details
   geometery_details = location_json.get("location").get("geometery")
   #geometery_details.pop("crs")  # removes the "crs" from geometry

   # includes city and location_coordinates
   location_details = {
     "cities": location_json.get("location").get("cities"),
     "coordinate": location_json.get("location").get("coordinate")
   }

   #EndDateTime
   end_datetime = location_json.get("EndDateTime")

   #StarDateTime
   start_datetime = location_json.get("StarDateTime")

   #State
   state = location_json.get("State")

   #gipodId
   gipod_id = location_json.get("gipodId")
   
   #adding all these details into another dict
   properties = {
     "gipodId": gipod_id,
     "StartDateTime": start_datetime,
     "EndDateTime": end_datetime,
     "state": state,
     "location": location_details
   }


   # creating the final dict to be returned.
   geojson_data_point = {
       "type": "Feature",
       "geometry" : geometery_details,
       "properties": properties
   }

   return geojson_data_point

def process_all_location_data(all_location_points):
    """
    For all the points in the location details we will  
    create the feature collection
    """

    feature_collection = {
         "type": "FeatureCollection",
         "features": []
    } #creates dict with zero features.

    for data_point in all_location_points:
        feature_collection.get("features").append(
            process_location_data(data_point)
        )

    return feature_collection


def fetch_details(url: str, file_name: str):
      # Makes request call to get the data of detail
        response = requests.get(url)
        print("Sending Request for details of gpodId: " + file_name)
        folder_path ='api_request_jsons/fetch_details/JSON unfiltered'
        text = json.dumps(response.json(),sort_keys=False, indent=4)
        print("Details extracted for: "+ file_name)
        save_file(folder_path,file_name,text)
        return response.json()
        # save_file(folder_path,GipodId,text2)
        # any other processe

def fetch_points(url: str):
       response = requests.get(url)
       folder_path ='api_request_jsons/fetch_points'
       text = json.dumps(response.json(),sort_keys=False, indent=4)
       print("Points Fetched, going to next step: Extracting details")
       for obj in response.json():
         all_location_points = [fetch_details(obj.get("detail"),str(obj.get("gipodId")))]
       save_file(folder_path,'points',text)
       feature_collection_json = process_all_location_data(all_location_points)
       text2 = json.dumps(process_all_location_data(all_location_points))
       folder_path2 = "api_request_jsons/fetch_details/Coordinates"
       file_name2 = "Converted"
       save_file(folder_path2,file_name2,text2)
       return feature_collection_json

def save_file(save_path: str, file_name: str, file_information: str):
        completeName = os.path.join(save_path, file_name +".json")
        print(completeName + " saved")
        file1 = open(completeName, "wt")
        file1.write(file_information)
        file1.close()

api_response_url = "http://api.gipod.vlaanderen.be/ws/v1/workassignment"
fetch_points(api_response_url)

解决方案

Based on #Edit 3 of the question, I have updated the complete solution. There are two issues.

  • Typo in function process_location_data. In this function, I was loading geometery instead of geometry (check the typo in spelling)


       # incorrect for code
       geometery_details = location_json.get("location").get("geometery")
    
       # correct one
       geometery_details = location_json.get("location").get("geometry")

Also, I found typos in state, endDateTime and startDateTime keys of the object. (fixed in the complete solution provided below)

  • Appending the list all_location_points in the fetch_points function.


    #Current code
    for obj in response.json():                                                                                               
        all_location_points = [                                                                                               
            fetch_details(obj.get("detail"), str(obj.get("gipodId")))                                                            
        ]            

In this all_location_points is getting updated each time with the obj, instead of appending it to the list.

# Fixed 

    all_location_points = []                                                                                                  
    for obj in response.json():                                                                                               
        all_location_points.append(                                                                                           
            fetch_details(obj.get("detail"), str(obj.get("gipodId")))                                                            
        )    

In the above answer, I had used shorthand for creating a list (list comprehension). the above 3 lines could be converted into a single line as

    all_location_points = [
      fetch_details(obj.get("detail"), str(obj.get("gipodId")))
      for obj in response.json()
    ]

The complete updated solution, (including typo fix and appending list)


    import requests
    import json
    import os
    import glob
    import shutil
    
    
    def process_location_data(location_json):
        """Converts the data point into required geojson format"""
    
        # assigning variable to store geometry details
        geometery_details = location_json.get("location").get("geometry")
        # geometery_details.pop("crs")  # removes the "crs" from geometry
    
        # includes city and location_coordinates
        location_details = {
            "cities": location_json.get("location").get("cities"),
            "coordinate": location_json.get("location").get("coordinate"),
        }
    
        # EndDateTime
        end_datetime = location_json.get("endDateTime")
    
        # StarDateTime
        start_datetime = location_json.get("startDateTime")
    
        # State
        state = location_json.get("state")
    
        # gipodId
        gipod_id = location_json.get("gipodId")
    
        # adding all these details into another dict
        properties = {
            "gipodId": gipod_id,
            "StartDateTime": start_datetime,
            "EndDateTime": end_datetime,
            "state": state,
            "location": location_details,
        }
    
        # creating the final dict to be returned.
        geojson_data_point = {
            "type": "Feature",
            "geometry": geometery_details,
            "properties": properties,
        }
    
        return geojson_data_point
    
    
    def process_all_location_data(all_location_points):
        """
        For all the points in the location details we will
        create the feature collection
        """
    
        feature_collection = {
            "type": "FeatureCollection",
            "features": [],
        }  # creates dict with zero features.
    
        for data_point in all_location_points:
            feature_collection.get("features").append(process_location_data(data_point))
    
        return feature_collection
    
    
    def fetch_details(url: str, file_name: str):
        # Makes request call to get the data of detail
        response = requests.get(url)
        print("Sending Request for details of gpodId: " + file_name)
        folder_path = "api_request_jsons/fetch_details/JSON unfiltered"
        text = json.dumps(response.json(), sort_keys=False, indent=4)
        print("Details extracted for: " + file_name)
        save_file(folder_path, file_name, text)
        return response.json()
        # save_file(folder_path,GipodId,text2)
        # any other processe
    
    
    def fetch_points(url: str):
        response = requests.get(url)
        folder_path = "api_request_jsons/fetch_points"
        text = json.dumps(response.json(), sort_keys=False, indent=4)
        print("Points Fetched, going to next step: Extracting details")
        all_location_points = []
        for obj in response.json():
            all_location_points.append(
                fetch_details(obj.get("detail"), str(obj.get("gipodId")))
            )
        save_file(folder_path, "points", text)
        feature_collection_json = process_all_location_data(all_location_points)
        text2 = json.dumps(process_all_location_data(all_location_points))
        folder_path2 = "api_request_jsons/fetch_details/Coordinates"
        file_name2 = "Converted"
        save_file(folder_path2, file_name2, text2)
        return feature_collection_json
    
    
    def save_file(save_path: str, file_name: str, file_information: str):
        completeName = os.path.join(save_path, file_name + ".json")
        print(completeName + " saved")
        file1 = open(completeName, "wt")
        file1.write(file_information)
        file1.close()
    
    
    api_response_url = "http://api.gipod.vlaanderen.be/ws/v1/workassignment"
    fetch_points(api_response_url)

这篇关于将JSON转换为QGIS GeoJSON:同时具有多种功能和不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆