[英]Reformat JSON file?
我有兩個JSON文件。
檔案A:
"features": [
{
"attributes": {
"NAME": "R T CO",
"LTYPE": 64,
"QUAD15M": "279933",
"OBJECTID": 225,
"SHAPE.LEN": 828.21510830520401
},
"geometry": {
"paths": [
[
[
-99.818614674337155,
27.782542677671653
],
[
-99.816056346719051,
27.782590806976135
]
]
]
}
}
檔案B:
"features": [
{
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[
-99.773315512624,
27.808875128096
],
[
-99.771397939251,
27.809512259374
]
]
]
},
"type": "Feature",
"properties": {
"LTYPE": 64,
"SHAPE.LEN": 662.3800009247,
"NAME": "1586",
"OBJECTID": 204,
"QUAD15M": "279933"
}
},
我希望將文件B重新格式化為類似於文件A。將“屬性”更改為“屬性”,將“坐標”更改為“路徑”,並同時刪除“類型”:“ MultiLineString”和“類型”:“功能”。 通過python做到這一點的最好方法是什么?
有沒有辦法對“屬性”鍵值對重新排序以使其看起來像文件A?
這是一個相當大的數據集,我想遍歷整個文件。
在Python中處理JSON是編程的輸入過程輸出模型的不錯選擇。
作為輸入,您可以使用json.load()
將外部JSON文件轉換為Python數據結構。
為了輸出,您可以使用json.dump()
將Python數據結構轉換為外部JSON文件。
對於處理或轉換步驟,請使用普通的Python dict
和list
方法執行所需的任何操作。
該程序可能會執行您想要的操作:
import json
with open("b.json") as b:
b = json.load(b)
for feature in b["features"]:
feature["attributes"] = feature["properties"]
del feature["properties"]
feature["geometry"]["paths"] = feature["geometry"]["coordinates"]
del feature["geometry"]["coordinates"]
del feature["geometry"]["type"]
del feature["type"]
with open("new-b.json", "w") as new_b:
json.dump(b, new_b, indent=1, separators=(',', ': '))
關於什么:
cat <file> | python -m json.tool
這會將文件的內容重新格式化為統一的人類可讀格式。 如果確實需要更改字段名稱,則可以使用sed。
cat <file> | sed -e 's/"properties"/"attributes"/'
這可能足以滿足您的用例。 如果您需要更細致的解析,則必須閱讀如何通過ORM庫管理JSON的知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.