打印json导致python

时间:2014-11-17 06:02:49

标签: python json command-line printing

我正在为这个项目使用两个文件。 Snapchat.py和test.py

Snapchat.py包含以下内容(显示重要部分):

def add_friend(self, username):
    """Add user as friend
    Returns JSON response.
    Expected messages:
        Success: '{username} is now your friend!'
        Pending: '{username} is private. Friend request sent.'
        Failure: 'Sorry! Couldn't find {username}'
    :param username: Username to add as a friend
    """
    r = self._request('friend', {
        'action': 'add',
        'friend': username,
        'username': self.username
    })
    return r.json()

我目前正在处理的文件test.py包含以下代码:

#including Snapchat in test.py
from snapchat import Snapchat

s = Snapchat()

username = raw_input('Enter your username: ')
password = raw_input('Enter your password: ')
friend = raw_input('Enter friend name: ')
s.login(username, password)

s.add_friend(friend)

这里的重要部分是:

    Returns JSON response.
    Expected messages:
        Success: '{username} is now your friend!'
        Pending: '{username} is private. Friend request sent.'
        Failure: 'Sorry! Couldn't find {username}'

我希望在命令shell中的test.py文件末尾打印该响应。

虽然我不知道如何执行此操作,但我已尝试将其导入test.py文件并打印,但无效。

1 个答案:

答案 0 :(得分:1)

请注意,您在问题中粘贴的邮件将通过add_friend方法返回,因此您无需执行任何操作。

只需打印就好;

#First you need to see what is the response for your login call
login_response = s.login(username, password)
print str(login_response)

#if you wish to access some value in this response
value = login_response.get("the_value", {the default value})

if value: #incase you want to make sure you logged in correctly   
    json_response = s.add_friend(friend)
    print str(json_response)