arzola arzola - 1 month ago 6
JSON Question

Reformat JSON file?

I have two JSON files.

File 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
]
]
]
}
}


File 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"
}
},


I would like File B to be reformatted to look like File A.
Change "properties" to "attributes", "coordinates" to "paths", and remove both "type": "MultiLineString" and "type": "Feature". What is the best way to do this via python?

Is there a way to also reorder the "attributes" key value pairs to look like File A?

It's a rather large dataset and I would like to iterate through the entire file.

Answer

Manipulating JSON in Python is a good candidate for the input-process-output model of programming.

For input, you convert the external JSON file into a Python data structure, using json.load().

For output, you convert the Python data structure into an external JSON file using json.dump().

For the processing or conversion step, do whatever it is that you need to do, using ordinary Python dict and list methods.

This program might do what you want:

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