我正在做一個專案,我將從各種檔案中檢索資料,然后這些資料將被寫入 geojson 格式的檔案中。
下面是一些代碼和輸出的簡化示例:
代碼:
def get_data(data):
features = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
data["lat"],
data["long"],
],
},
"properties": {
"obsid": data["file_name"],
"name": data["guid_id"],
"h_gs": data["z"],
},
}
],
}
for id, top, bot, code in zip(
data["id"],
data["top"],
data["bot"],
data["code"],
):
info = {
id: {
"top": top,
"bot": bot,
"code": code,
},
}
features["features"].append(info)
return features
def main(data):
data = get_data(data)
to_json = json.dumps(data, indent=4)
print(to_json)
if __name__ == "__main__":
# example data
data = {
"lat": 40.730610,
"long": -73.935242,
"z": 28.37,
"file_name": "tmrx.txt",
"guid_id": "d4d5b10a-c5fc-450a-9b3b-f309e7cb9613",
"id": ["id_0", "id_1", "id_2", "id_3", "id_4"],
"top": [100, 200, 300, 400, 500],
"bot": [90, 190, 290, 390, 490],
"code": ["a", "b", "c", "d", "e"],
}
main(data)
輸出:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
40.73061,
-73.935242
]
},
"properties": {
"obsid": "tmrx.txt",
"name": "d4d5b10a-c5fc-450a-9b3b-f309e7cb9613",
"h_gs": 28.37
}
},
{
"id_0": {
"top": 100,
"bot": 90,
"code": "a"
}
},
{
"id_1": {
"top": 200,
"bot": 190,
"code": "b"
}
},
{
"id_2": {
"top": 300,
"bot": 290,
"code": "c"
}
},
{
"id_3": {
"top": 400,
"bot": 390,
"code": "d"
}
},
{
"id_4": {
"top": 500,
"bot": 490,
"code": "e"
}
}
]
}
這很好用,但我希望我能讓輸出看起來有點不同。
期望的輸出:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
40.73061,
-73.935242
]
},
"properties": {
"obsid": "tmrx.txt",
"name": "d4d5b10a-c5fc-450a-9b3b-f309e7cb9613",
"h_gs": 28.37
}
"id_0": {
"top": 100,
"bot": 90,
"code": "a"
}
"id_1": {
"top": 200,
"bot": 190,
"code": "b"
}
"id_2": {
"top": 300,
"bot": 290,
"code": "c"
}
"id_3": {
"top": 400,
"bot": 390,
"code": "d"
}
"id_4": {
"top": 500,
"bot": 490,
"code": "e"
}
}
]
}
在那里,洗掉了“不必要的”括號。
論壇上有沒有人知道我如何在上面的代碼中實作這個結果?
最好的問候, 米凱爾
請參閱上面的代碼示例。
uj5u.com熱心網友回復:
在您的代碼中更改以下行
features["features"].append(info)
對此
features["features"][0] |= info
uj5u.com熱心網友回復:
而不是features["features"].append(info)使用:
features["features"][0].update(info)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524507.html
