重新格式化 JSON 文件?

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。 将 "properties" 更改为 "attributes",将 "coordinates" 更改为 "paths",并删除 "type":"MultiLineString" 和 "type":"Feature".通过 python 执行此操作的最佳方法是什么?

有没有办法将 "attributes" 键值对也重新排序,使其看起来像文件 A?

这是一个相当大的数据集,我想遍历整个文件。

怎么样:

cat <file> | python -m json.tool

这会将文件内容重新格式化为统一的人类可读格式。如果您确实需要更改字段的名称,您可以使用 sed。

cat <file> | sed -e 's/"properties"/"attributes"/'

这对于您的用例可能就足够了。如果您需要更细致的解析,则必须阅读如何通过 ORM 库管理 JSON。

在 Python 中操作 JSON 是 input-process-output model 编程的一个很好的候选人。

对于输入,您使用 json.load().

将外部 JSON 文件转换为 Python 数据结构

对于输出,您使用 json.dump().

将 Python 数据结构转换为外部 JSON 文件

对于处理或转换步骤,使用普通的 Python dictlist 方法,做您需要做的任何事情。

这个程序可能会做你想做的事:

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=(',', ': '))