Unable to avoid list items in JSON file from being printed in new lines

Viewed 125

edit problem solved thanks to Oyono and chepner!

I'm trying to save a dictionary which includes long lists as a JSON file, without having each new item in the lists in a new line. to save the dictionary, I'm using the command:

with open('file.json', 'w') as fp:
    json.dump(coco, fp, indent=2)

The file is really big and I can not open it in Colab. so when I open it using VSC it's shown each item in the list in a separate line. when I try to print only a small part of the dictionary in the Colab I'm getting everything in a single line.

Any ideas why could it happen or how to avoid it? this is how it's look like in VSC:

  "annotation": [
    {
        "segmentation": [
            [
                75.0,
                74.5,
                ...(many more lines like this),
                435.0,
                435.5
            ]
        ],
        "iscrowd": 0,
        "category_id": 1,
        "image_id": 43,
        "id": 430,
        "bbox": [
            11.0,
            280.0,
            117.0,
            156.0
        ],
        "area": 9897,
    }
  ],
  ]
}

And this is how I want it to look (and can't tell if there is actual difference between the files)

{
 "segmentation": [ [ 316.0, 171.5, 320.5, 168.0, 332.5, 153.0, 332.5, 149.0, 330.0, 146.5, 305.0, 134.5, 292.0, 125.5, 280.0, 120.5, 275.0, 116.5, 270.0, 115.5, 261.5, 130.0, 258.0, 133.5, 251.5, 136.0, 255.0, 140.5, 282.0, 153.5, 285.0, 156.5, 289.0, 156.5, 296.0, 159.5, 310.0, 170.5, 316.0, 171.5 ] ],
                "iscrowd": 0,
                "image_id": 5,
                "category_id": 1,
                "id": 5,
                "bbox": [ 251.5, 115.5, 81.0, 56.0 ],
                "area": 2075.0
},
1 Answers

You have to remove indent=2 in your call to dump:

with open('file.json', 'w') as fp:
    json.dump(coco, fp)

The indent keyword will save your dictionary object as a pretty printed json object, which means printing each list item in individual lines. You can try this in a python console to see how indent influences your output json:

json.dumps({1: "a", "b": [1, 2]}, indent=2)
# will output: '{\n  "1": "a",\n  "b": [\n    1,\n    2\n  ]\n}'
json.dumps({1: "a", "b": [1, 2]})
# will output: '{"1": "a", "b": [1, 2]}'
Related