python - 如何解决从错误的 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'))
解决方案
文件结构和实际 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)
推荐阅读
- c# - 将 vb6“类型”(结构)转换为 c# 的最佳方法
- javascript - Mobx 强制计算值更新
- c - 在基于 ncurses 的程序中拦截 SIGWINCH 后,无法识别按键
- json - 如何遍历 mongodb 中的嵌套嵌套文档?
- python-3.x - 用数组获取对应的字段元素
- java - 包括 spring boot 端点路径变量作为度量维度
- ruby-on-rails - 无法使用 linux mint 19 在 ruby on rails 中生成模型
- css - 表格单元格间距不均匀
- sql - sql : 在 order by 中选择任何更改的第一行
- jms - Log4j 2.11.1 JMS appender 编程错误