【发布时间】:2020-01-24 19:35:05
【问题描述】:
我有一个包含多个顺序 JSON 对象的大文本文件。据我所知,单独解释/加载 JSON 对象的最佳方法是从文本文件中获取它们并将它们放在单独的行中,以便我可以逐行遍历它们。
不幸的是,我无法让 python 将它们分成单独的行,而不会破坏 JSON 结构到难以辨认的程度。此外,这些文件非常大,并且包含大量信息。请让我知道最好的方法是 a) 将不同的 JSON 对象字符串放到 python 中的不同行上,或者 b) 单独解析信息的更好方法。
文件中的文本如下所示:
"{\"time\":\"Fri Aug 09 18:55:37 +0000 2019\", \"id\":720,\"text\":\"I'd really like to find a good solution to this problem.\",\"source\":\"href=\\\"http:\\/\\/stackoverflow.com\\\",\"lang\":\"en\",\"timestamp_ms\":\"1565376937344\"}\r\n""{\"time\":\"Sat Aug 10 22:16:00 +0000 2019\", \"id\":721,\"text\":\"And I would appreciate your help!\",\"source\":\"href=\\\"http:\\/\\/stackoverflow.com\\\",\"lang\":\"en\",\"timestamp_ms\":\"156534564531\"}\r\n""{\"time\":\"Sun Aug 09 18:55:37 +0000 2019\", \"id\":720,\"text\":\"Imagine additional text repeating below.\",\"source\":\"href=\\\"http:\\/\\/stackoverflow.com\\\",\"lang\":\"en\",\"timestamp_ms\":\"1565376937344\"}\r\n"
如果将上述文本分配给python对象并要求python打印它,python会返回我想看到的,即:
{"time":"Fri Aug 09 18:55:37 +0000 2019", "id":720,"text":"I'd really like to find a good solution to this problem.","source":"href=\"http:\/\/stackoverflow.com\","lang":"en","timestamp_ms":"1565376937344"}
{"time":"Sat Aug 10 22:16:00 +0000 2019", "id":721,"text":"And I would appreciate your help!","source":"href=\"http:\/\/stackoverflow.com\","lang":"en","timestamp_ms":"156534564531"}
{"time":"Sun Aug 09 18:55:37 +0000 2019", "id":720,"text":"Imagine additional text repeating below.","source":"href=\"http:\/\/stackoverflow.com\","lang":"en","timestamp_ms":"1565376937344"}
但是,如果我将文件读取到 python 对象并打印该对象,我会得到原始文本。我试过f.read()、readline()、readlines()、splitlines()(这给了我一堆额外的\\s),我试过用splitstring()分割字符串。我很茫然,我承认我对编码还很陌生,从来没有真正坐下来学习基础知识。
您可以给我的任何帮助来获取上述文本并最终将它们翻译成单独的 JSON 对象并阅读,例如,每个文本都会很棒。我的最终目标是能够从各个 json 对象中调用字典键,如下所示:
for line in f:
data = json.loads(line)
print(data[‘text’])
并得到以下列表
"I'd really like to find a good solution to this problem."
"And I would appreciate your help!"
"Imagine additional text repeating below."
【问题讨论】:
-
您能否发布(在代码块中)您文件的确切内容的子集?没有重复的引号或任何东西。
-
@martineau 它更多的是使用内联代码刻度的多行文本,但回想起来,我想不出更好的方法来做到这一点,因为 OP 将它粘贴为一行而不是几行。跨度>
-
不幸的是,上面粘贴的内容(第一个代码块)正是我的文件中的内容,重复的引号和所有内容。另外不幸的是,第一个块 是 一行,所以我按原样粘贴了它。感谢您的格式化帮助。
-
@RachelSamuels 在一行文本中?不是多行?
-
我同意,问题是生成数据的任何东西都没有正确执行。它看起来像字符串的 Python 表示形式,并且不是有效的 JSON 格式。