1

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

  • Update your Python to at least 3.7+ and watch the magic happen. – matszwecja Apr 28 '22 at 12:10
  • If you are forced to use 3.4, see https://stackoverflow.com/questions/43789439/python-json-loads-changes-the-order-of-the-object But JSON defines objects as an unordered collection, so your file is still valid. – ivvija Apr 28 '22 at 12:18
  • 1
    I dont have to be strict about python version. I am using Python3.8 now, and I dont see the issue anymore! I really appreciate quick response! Thank you so much! @matszwecja – Akshay Moharir Apr 28 '22 at 13:01
  • @AkshayMoharir posted as an answer in case you want to accept. – matszwecja Apr 28 '22 at 13:06

1 Answers1

0

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.

matszwecja
  • 6,357
  • 2
  • 10
  • 17