Python报告“ValueError:无法解码JSON对象”

时间:2017-06-15 12:57:56

标签: python json

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

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

2 个答案:

答案 0 :(得分:10)

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)

答案 1 :(得分:2)

这应该这样做:

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