简体   繁体   English

在python中打印json结果

[英]Printing json results in python

I'm using two files for this project. 我正在为该项目使用两个文件。 Snapchat.py and test.py Snapchat.py和test.py

Snapchat.py contains the following (showing the important part): 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()

The file test.py, that I am currently working on has the following code: 我当前正在处理的文件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)

The important part here is: 这里的重要部分是:

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

I want that response printed at the end of the test.py file in the command shell. 我希望该响应打印在命令外壳的test.py文件的末尾。

Though I have no clue on how to do this, I have tried importing it in the test.py file and printing it, but not working. 尽管我不知道如何执行此操作,但是我尝试将其导入到test.py文件中并进行打印,但无法正常工作。

Please note that the Messages you pasted in your question will infact be returned by the add_friend method, so you don't need to do anything. 请注意,您粘贴在问题中的消息实际上将由add_friend方法返回,因此您无需执行任何操作。

Simply print them like; 只需像打印它们一样;

#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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM