【问题标题】:Python: Saving GeoJSON after convertion from JSON as a JSON/GeoJSONPython:将 JSON 从 JSON 转换为 JSON/GeoJSON 后保存
【发布时间】:2021-05-22 09:43:13
【问题描述】:

注意这个问题是这个问题的延续:

Converting JSON to QGIS GeoJSON: while having multiple features and different types

经过一些帮助后,我设法将一些 JSON 转换为在 QGIS 中应该可读的 GeoJSON。问题是功能已经完成,我仍然需要保存文件来测试它们。

问题是,虽然我知道如何保存 JSON 文件,甚至为它创建了一个特殊的功能,但我不知道如何保存这些 JSON 文件已更改,目前我正在保存这些 JSON 文件,但现在我想保存它们已更改。

import requests
import json
import os
import glob
import shutil

# response = requests.get("http://api.gipod.vlaanderen.be/ws/v1/workassignment", params = {"CRS": "Lambert72"})

# text = json.dumps(response.json(),sort_keys=True, indent=4)
# print(text)

# f = open("text.json", "wt")
# f.write(text)
# print(response.status_code)


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)
    folder_path = 'api_request_jsons/fetch_details/JSON unfiltered'
    text = json.dumps(response.json(), sort_keys=False, indent=4)
    print(text)
    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")
    i = 1
    for obj in response.json():
        # Printing object id for confirmation
        print("fetching object detais from gipodId " + str(obj.get("gipodId")))
        file_name = str(obj.get("gipodId"))
        # Getting the object details
        all_location_points = [fetch_details(obj.get("detail"), file_name)]
    save_file(folder_path, 'points', text)
    feature_collection_json = process_all_location_data(all_location_points)
    return feature_collection_json
    print(feature_collection_json)
    # text2 = text[int('coordinate')]
    # print(text2)


def save_file(save_path: str, file_name: str, file_information: str):
    completeName = os.path.join(save_path, file_name + ".json")
    print(completeName)
    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)

那么我如何使用我制作的 save_file 函数来做到这一点?

【问题讨论】:

    标签: python json geojson


    【解决方案1】:

    我已经找到了我的问题的答案,我在下面发布了代码。很明显我应该怎么做,但是看到我应该把保存命令放在哪里有点乱。

    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)
    

    但现在在 QGIS 中测试转换后的 JSON 文件后,我发现这些 JSON 返回为没有几何的 GeoJSON。我还有其他问题,但您可以在上一个主题中找到。

    【讨论】:

      猜你喜欢
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2018-10-11
      • 2015-08-07
      相关资源
      最近更新 更多