Home > Software engineering >  How to append element at the end in json file using python?
How to append element at the end in json file using python?

Time:04-29

I have hundreds of thousands of json files with annotations info in them. Example json file:

{
  "version": "4.5.4",
  "flags": {
    "flag1": false,
    "surface": false,
    "gtype": false,
    "light": false
  },
  "shapes": [
    {
      "label": "object-1",
      "points": [
        [
          100.5,
          105.65423
        ]
      ],
      "group_id": null,
      "shape_type": "point",
      "flags": {}
    },
    {
      "label": "assembly",
      "points": [
        [
          31.8416,
          52.546
        ],
        [
          65,
          97
        ]
      ],
      "group_id": null,
      "shape_type": "rectangle",
      "flags": {}
    }
  ],
  "location": "/data/abc.bmp",
  "Data": null,
  "Height": 540,
  "Width": 960
}

I want to add element at the end of json file. say, element name is path and it is a string, then my desired output should look like,

... existing data in json ...
... existing data in json ...

  "location": "/data/abc.bmp",
  "Data": null,
  "Height": 540,
  "Width": 960,
  "path": "/data/pqr.pgm"
}

I have python code which does add element to the json file, but it re-arranges contents of file. Following is how my code reads json

with open(jsonFileName,"r") as jsonFile:
            jsonData = json.loads(jsonFile.read())

And following is how I am adding new element to the file

jsonData['path'] = pathValueString
with open(jsonFileName, "w") as outputJsonFile:                    
    outputJsonFile.seek(0,2)
    json.dump(jsonData, outputJsonFile, indent=4)

Python version : 3.4.10

CodePudding user response:

Up to Python 3.6, standard dicts were unordered, meaning there was no guarantee that when json was loaded and saved order of keys would remain the same. There was possibility of using from collections import OrderedDict but of course making it work for json.loads wasn't trivial.

Since 3.7, dict objects are guaranteed to keep insertion order, so you can use it to keep the order as in the original file.

  • Related