natsuki_2002
natsuki_2002

Reputation: 25349

Python Cherrypy: dictionary not behaving like a dictionary

I'm trying to scrape some data using the Spotify API. The code below works and returns a lot of text when I search for the track name 'if i can't'. The beginning of the output from the API prints on my website and looks like this:

enter image description here

It looks like a dictionary except for the funny b' at the start. Also I can't access it like a dictionary. If I try

return raw_data['info']

it throws up an error. Similarly, if I try to find its type (so return type(raw_data) instead of return raw_data), the page comes up blank.

Is there someway to save the output from the data.read() in the form of a dictionary? Using

raw_data = ast.literal_eval(raw_data)

throws up an error.

#!/usr/local/bin/python3.2
# -*- coding: utf-8 -*-
import cherrypy
import numpy as np
import urllib.request

class Root(object):
    @cherrypy.expose
    def index(self):

            a_query = Query()
            text = a_query.search()

            return '''<html>
            Welcome to Spoti.py! %s
            </html>''' %text

class Query():

    def __init__(self):
        self.qstring = '''if i can't'''

    def space_to_plus(self):
        '''takes the instance var qstring
        replaces ' ' with '+' 
        -----------------------
        returns nothing'''

        self.qstring = self.qstring.replace(' ', '+')    

    def search(self):
        self.space_to_plus()

        url = 'http://ws.spotify.com/search/1/track.json?q=' + self.qstring
        data = urllib.request.urlopen(url)

        raw_data = data.read()

        #return raw_data['info']
        #return type(raw_data)

        return raw_data


cherrypy.config.update({
    'environment': 'production',
    'log.screen': False,
    'server.socket_host': '127.0.0.1',
    'server.socket_port': 15850,
    #'tools.encode.on': True,
    #'tools.encode.encoding': 'utf-8',
})

cherrypy.config.update({'tools.sessions.on': True})

cherrypy.quickstart(Root())

Upvotes: 0

Views: 290

Answers (1)

Claudiu
Claudiu

Reputation: 229381

What you have there is a JSON string. The b at the beginning indicates you are printing a a byte string literal. What you have to do is parse the JSON. Simply do this:

import json
...
info_dict = json.loads(raw_data)

Upvotes: 1

Related Questions