【问题标题】:Python reports "ValueError: No JSON object could be decoded"Python 报告“ValueError:无法解码任何 JSON 对象”
【发布时间】:2017-06-15 12:57:55
【问题描述】:

我在尝试将对象提取到特定元素时收到此错误消息

Traceback (most recent call last):
  File "twitter_mining.py", line 17, in <module>
    tweets_data = json.loads(tweets_data_path)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

我的代码

tweets_data_path = 'data.txt'
tweets_data = json.loads(tweets_data_path)
tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)

数据 - http://intellij.my/rnd/nlp/sentiment-analysis/data.txt

【问题讨论】:

  • json.loads 需要 JSON 字符串,而不是包含可能包含 JSON 的文件路径的字符串。

标签: python json


【解决方案1】:

json.loads 不接受文件名作为参数。

读取文件的内容并将其传递给loads

tweets_data_path = 'data.txt'
with open(tweets_data_path) as file:
    tweets_data = json.loads(file.read())

或使用load

tweets_data_path = 'data.txt'
with open(tweets_data_path) as file:
    tweets_data = json.load(file)

【讨论】:

    【解决方案2】:

    应该这样做:

    with open('data.txt') as tweets_data_path:
        tweets_data = json.load(tweets_data_path)
    

    【讨论】:

      猜你喜欢
      • 2015-01-04
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多