a12*_*234 1 python json reformatting
我有两个 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
]
]
]
}
}
Run Code Online (Sandbox Code Playgroud)
文件乙:
"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"
}
},
Run Code Online (Sandbox Code Playgroud)
我希望将文件 B 重新格式化为文件 A。将“属性”更改为“属性”,将“坐标”更改为“路径”,并删除“类型”:“MultiLineString”和“类型”:“功能”。通过python执行此操作的最佳方法是什么?
有没有办法重新排序“属性”键值对,使其看起来像文件 A?
这是一个相当大的数据集,我想遍历整个文件。
在 Python 中操作 JSON 是编程的输入-过程-输出模型的一个很好的候选者。
对于输入,您将外部 JSON 文件转换为 Python 数据结构,使用json.load().
对于输出,您使用 .json 将 Python 数据结构转换为外部 JSON 文件json.dump()。
对于处理或转换步骤,使用普通的 Pythondict和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=(',', ': '))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1250 次 |
| 最近记录: |