编程语言
首页 > 编程语言> > 使用PRAW从Python中解码Reddit API中的JSON

使用PRAW从Python中解码Reddit API中的JSON

作者:互联网

我在Python / GTK应用程序中使用PRAW for Reddit API.我已成功使用API​​,但似乎无法解码JSON以供使用.应该知道我是Python和GTK应用程序的初学者.

# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE

import gettext
from gettext import gettext as _
gettext.textdomain('redditreader')

from gi.repository import Gtk # pylint: disable=E0611
import logging
logger = logging.getLogger('redditreader')

from redditreader_lib import Window
from redditreader.AboutRedditreaderDialog import AboutRedditreaderDialog
from redditreader.PreferencesRedditreaderDialog import PreferencesRedditreaderDialog

import praw

import json
import simplejson
from pprint import pprint

# See redditreader_lib.Window.py for more details about how this class works
class RedditreaderWindow(Window):
    __gtype_name__ = "RedditreaderWindow"

    def finish_initializing(self, builder): # pylint: disable=E1002
        """Set up the main window"""
        super(RedditreaderWindow, self).finish_initializing(builder)

        self.AboutDialog = AboutRedditreaderDialog
        self.PreferencesDialog = PreferencesRedditreaderDialog

        # Code for other initialization actions should be added here.
r = praw.Reddit(user_agent='example')
try:
    submissions = r.get_front_page(limit=5)
    [str(x) for x in submissions]
    jsondatafirst = simplejson.loads(str(submissions))
    jsondata = unicode(jsondatafirst, 'utf-8')
    print(jsondata)
except (simplejson.decoder.JSONDecodeError, ValueError):
    print 'Decoding JSON has failed'

解决方法:

使用PRAW,您不需要进行任何json解码,因为PRAW会为您处理所有这些.

例如,对于每个提交,您要打印出upvotes的数量,downvotes的数量和提交标题.你可以这样做:

for submission in r.get_front_page(limit=5):
    print submission.ups, submission.downs, submission.title

如果要查看可在提交对象上使用的所有属性,可以运行:

import pprint
for submission in r.get_front_page(limit=5):
    pprint.pprint(vars(submission))

此外,如果您想从提交中获取评论,则可以使用submission.comments属性.您还可以手动查看请求的json响应,以查看PRAW(example)应该提供哪些属性.

未在对象的任何位置明确列出属性,因为属性是直接从关键名称在请求的关联json响应中创建的.

标签:python,json,api,gtk,reddit
来源: https://codeday.me/bug/20190901/1785311.html