【问题标题】:Python Traceback Error When Reading Json File读取 Json 文件时出现 Python Traceback 错误
【发布时间】:2019-12-19 13:56:55
【问题描述】:

我刚刚将我所有的高音扬声器历史提取到一个 json 文件中。所以我想用python对推文做一些数据分析。我打开终端并输入以下命令从 python 中转储 json。

>>> import json
>>> with open('tweet.js') as json_file:
...     data = json.load(json_file)
...     print(data)

得到了这个“回溯”错误

 Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\George\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\George\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 4771: character maps to <undefined>

json 文件名为 tweet.js,它遵循这种形式

{
  "retweeted" : false,
  "source" : "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>",
  "entities" : {
    "hashtags" : [ ],
    "symbols" : [ ],
    "user_mentions" : [ {
      "name" : "Florin Pop \uD83D\uDC68\uD83C\uDFFB‍\uD83D\uDCBB",
      "screen_name" : "florinpop1705",
      "indices" : [ "0", "14" ],
      "id_str" : "861320851",
      "id" : "861320851"
    } ],
    "urls" : [ ]
  },
  "display_text_range" : [ "0", "155" ],
  "favorite_count" : "0",
  "in_reply_to_status_id_str" : "1194246195243302913",
  "id_str" : "1200417547524493312",
  "in_reply_to_user_id" : "861320851",
  "truncated" : false,
  "retweet_count" : "0",
  "id" : "1200417547524493312",
  "in_reply_to_status_id" : "1194246195243302913",
  "created_at" : "Fri Nov 29 14:13:40 +0000 2019",
  "favorited" : false,
  "full_text" : "@florinpop1705 I've heard good things about it, but never tried it.... Using kdenlive is simple yet some things are difficult to implement like text effect",
  "lang" : "en",
  "in_reply_to_screen_name" : "florinpop1705",
  "in_reply_to_user_id_str" : "861320851"
}

【问题讨论】:

  • 您提供的 sn-p 是有效的 JSON。您没有给出的是带有错误的实际完整回溯,因此我们可以看到它抱怨什么
  • 只是澄清一下:没有“回溯错误”,有一个“错误回溯”,从应用程序的入口点到发生错误的地方的堆栈跟踪。
  • @miatech 您面临的错误是:“UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 276: character maps to ” 请更新完整的回溯错误。查看提到的解决方案。
  • @roganjosh 我刚刚更新了错误输出...检查一下。我包括了编码,但没有解决它
  • @Vaibhav Jadhav 刚刚更新了错误输出

标签: python json data-analysis tweets


【解决方案1】:

这个解决方案会给你输出,encoding="utf8"必须加。你在打开文件时指定编码:

import json
with open("tweet.json", encoding="utf8") as json_file:
    data = json.load(json_file)
print(data)

【讨论】:

  • 还是报错...我认为是json文件,它有扩展名js,我认为是格式什么的,因为我可以打开其他json文件没问题
  • @miatech 我已经使用你的 json 文件来检查输出,它按照解决方案工作。
猜你喜欢
  • 2020-10-11
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
相关资源
最近更新 更多