首页 > 解决方案 > 如何解决从错误的 json 格式解码的问题

问题描述

每个人。需要帮助打开和阅读文件。

得到了这个 txt 文件 - https://yadi.sk/i/1TH7_SYfLss0JQ

这是一本字典

{"id0":"url0", "id1":"url1", ..., "idn":"urln"}

但它是使用 json 写入 txt 文件的。

#This is how I dump the data into a txt    
json.dump(after,open(os.path.join(os.getcwd(), 'before_log.txt'), 'a')) 

所以,文件结构是 {"id0":"url0", "id1":"url1", ..., "idn":"urln"}{"id2":"url2", "id3":"url3 ", ..., "id4":"url4"}{"id5":"url5", "id6":"url6", ..., "id7":"url7"}

这都是一个字符串....

我需要打开它并检查重复的ID,删除并再次保存。

但是得到 - json.loads 显示 ValueError: Extra data

尝试了这些: 如何从大文件中读取行分隔的 JSON(逐行) Python json.loads 显示 ValueError: Extra data json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

但仍然得到那个错误,只是在不同的地方。

现在我做到了:

with open('111111111.txt', 'r') as log:
    before_log = log.read()
before_log = before_log.replace('}{',', ').split(', ')

mu_dic = []
for i in before_log:
    mu_dic.append(i)

这消除了连续几个 {}{}{} 字典/json 的问题。

也许有更好的方法来做到这一点?

PS这是文件的制作方式:

json.dump(after,open(os.path.join(os.getcwd(), 'before_log.txt'), 'a'))    

标签: pythonjsonpython-3.x

解决方案


文件结构和实际 json 格式之间的基本区别是缺少逗号并且行没有包含在[. 所以同样可以用下面的代码片段来实现

with open('json_file.txt') as f:
    # Read complete file
    a = (f.read())

    # Convert into single line string
    b = ''.join(a.splitlines())

    # Add , after each object
    b = b.replace("}", "},")

    # Add opening and closing parentheses and ignore last comma added in prev step
    b = '[' + b[:-1] + ']'

x = json.loads(b)

推荐阅读