无法避免以新行打印 JSON 文件中的列表项

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

编辑 感谢 Oyono 和 chepner 解决了问题!

我正在尝试将包含长列表的字典保存为 JSON 文件,而不是将列表中的每个新项目都放在新行中。 为了保存字典,我使用命令:

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

文件很大,我用Colab打不开。所以当我使用 VSC 打开它时,它会在单独的行中显示列表中的每个项目。 当我尝试在 Colab 中只打印字典的一小部分时,我在一行中得到了所有内容。

知道为什么会发生或如何避免吗? 这是它在 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,
    }
  ],
  ]
}

这就是我想要的样子(无法判断文件之间是否存在实际差异)

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

您必须在对 dump 的调用中删除 indent=2

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

indent 关键字会将您的字典对象保存为漂亮的打印 json 对象,这意味着在单独的行中打印每个列表项。 您可以在 python 控制台中尝试此操作以查看 indent 如何影响您的输出 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]}'