如何使用python修复JSON?

3htmauhk  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(215)

我的JSON文件看起来像这样:

{
    "key": "test", "expiry": "test",
    "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13",
    "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13",
    "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expiry": "2022-12-13",
}

我希望它删除最后一个“”,这样JSON就不会有任何错误。我该怎么做呢?错误是最后一个,在文件中:https://prnt.sc/mNVxXWOVBAOS
我如何做到这一点与加载文件,然后这样做,它立即写入修复的版本到文件?
我想做的

comma_index = x.rfind(',')
                    s_cleaned = x[:comma_index] + x[comma_index+1:]

但没有成功。

fnx2tebb

fnx2tebb1#

您的代码工作正常:

import json

x = '''{
    "key": "test", "expiry": "test",
    "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13",
    "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13",
    "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expiry": "2022-12-13",
}'''

comma_index = x.rfind(',')
s_cleaned = x[:comma_index] + x[comma_index+1:]
print(s_cleaned)

t = json.loads(s_cleaned)
print(t)

输出量:

{
    "key": "test", "expiry": "test",
    "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13",
    "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13",
    "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expiry": "2022-12-13"
}

{'key': '91a969af-263f-46c1-a2f3-12e876403de6', 'expiry': '2022-12-13'}

相关问题