Python 3.5.1: NameError: 名称'json'未定义

12
#!/usr/bin/env python
# encoding: utf-8

import tweepy #https://github.com/tweepy/tweepy
import json as simplejson


    #write tweet objects to JSON
    file = open('tweet.json', 'wb') 
    print ("Writing tweet objects to JSON please wait...")
    for status in alltweets:
        json.dump(status._json,file,sort_keys = True,indent = 4)

    #close the file
    print ("Done")
    file.close()

if __name__ == '__main__':
    #pass in the username of the account you want to download
    get_all_tweets("@AlertZaAfrica")

Python编译器指出第54行有错误。我已经将import json定义为simplejson。上面的区域展示了我定义import json的位置。


请展示一下你定义它的地方。 - nick_gabpe
3
那就是原因了……你的意思是要做 import simplejson as json 吗?既然你已经使用 Python 3.5,为什么不直接写成 import json 呢? - Jon Clements
好的,让我分享完整的代码。 - rabeshi1010
1
import simplejson as json - ferdy
1个回答

24

你需要先在系统中安装simplejson才能导入它:

$ sudo pip3 install simplejson

现在你可以在代码中导入它:

import simplejson as json

从现在开始,您将能够使用json访问simplejson包。

请注意,如果您仍在使用Python 2(尽管这不是OP的原始问题),您应该执行

$ sudo pip install simplejson

改为使用“instead”。


1
我已经安装了它,但我的Python仍然找不到它。 - ScottyBlades
@ScottyBlades 我猜你的系统Python版本不是3。既然这里的问题是关于Python3的,你可能应该简单地使用pip install simplejson,这样你的系统Python(可能是版本2)就会安装simplejson包。希望对你有所帮助。 - ferdy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接