Cant parse a dictionary retrieved from xmlhttprequest.responseText [SOLVED]

In my program, I make a call to my python script to return a dictionary. I am trying to access this dictionary in JavaScript after completing the XMLHttpRequest. response text. The dictionary will appear however, I am not able to parse it.

For example: calling this,responseText[‘Username’]; returns undefined

I have tried stringifying the responseText and then parsing it, which hasn’t helped at all. What am I doing wrong? I have been stuck on this for too long

Requested function:

def getBasicInfo():
    dict = {}
    list = []
    username = ud["username"]
    displayName = ide["displayName"]
    accountCreationDate = ud['creationTime']
    following = fol["followingUsersCount"]
    followers = fol['followerCount']
    playlistCount = len(ply["playlists"])
    playlists = ply["playlists"]

    dict.update({"Username": username})
    dict.update({"Display Name": displayName})
    dict.update({"Account Creation Date": accountCreationDate})
    dict.update({"Following": str(following)})
    dict.update({"Followers": str(followers)})
    dict.update({"Number of playlists": str(playlistCount)})

    for x in range(0, len(ply["playlists"])):
        list.append(playlists[x]["name"])

    dict.update({"Playlist names": list})
    totalNumberSongs = len(sh1) + len(sh2) + len(sh3)
    firstTime = sh1[0]['endTime']
    lastTime = sh3[-1]['endTime']
    dict.update({"Total Number of Songs Analyzed": str(totalNumberSongs)})
    timeStamp = firstTime + " to " + lastTime
    dict.update({"Data Lifecycle": timeStamp})
    return dict

Python Script:

#!\Users\bobs\anaconda3\python.exe         #Python Interpreter
from data import *
import cgi
import sys

fs = cgi.FieldStorage()

sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")

if "basic" in fs.keys():
    info = getBasicInfo()
    print(info)

if "artist" in fs.keys():
    artist = countArtistsDesc()
    print(artist)

if "song" in fs.keys():
    song = countSongsDesc()
    print(song)

if "day" in fs.keys():
    day = getHighestPlayedDays(True)
    print(day)

if "playlist" in fs.keys():
    playlist = getPlaylist()
    print(playlist)

sys.stdout.write("\n")
sys.stdout.close()

HTML Page/XMLHTTPRequest:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Basic Info</title>
</head>
<body style="background-color:#1DB954">
<h1 align="center">User's Basic Info</h1>
<script>
    var http = new XMLHttpRequest();
    http.open('GET', '/cgi-bin/simpleData.py?basic=True', true);
    http.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    // http.responseType = 'json'
    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("responseText").innerHTML = this.responseText;
            document.getElementById("problem").innerHTML = this.responseText['Username'];
        }
    };
    http.send(null);
</script>
<p id="responseText"></p>
<p id="problem"></p>
</body>
</html>

Output:

{'Username': 'bobsmith123', 'Display Name': 'Bob Smith', 'Account Creation Date': '2016-10-10', 'Following': '34', 'Followers': '46', 'Number of playlists': '32', 'Playlist names': ['5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party 🍻', 'Rap', 'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies', 'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020', 'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour', 'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP", 'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld 🎢🎡🎠', 'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'], 'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'}

undefined

Solution:

#Very end of getBasicInfo()
return json.dumps(dict, separators=(',', ':'))
#After readyState == 4 && this.status == 200 in the HTML page
parsed = JSON.parse(this.responseText);

1 thought on “Cant parse a dictionary retrieved from xmlhttprequest.responseText [SOLVED]”

  1. This is because python represents strings with single quotes, and json requires double quotes.

    import json;
    body = {'Username': 'bobsmith123', 'Display Name': 'Bob Smith', 
            'Account Creation Date': '2016-10-10', 'Following': '34', 
            'Followers': '46', 'Number of playlists': '32',
            'Playlist names': [
                '5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party 🍻', 'Rap', 
                'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies', 
                'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020', 
                'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour', 
                'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP", 
                'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld 🎢🎡🎠', 
                'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'], 
            'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'
        }
    print(json.dumps(body))
    

    That produces the output in the correct format

    
    {"Username": "bobsmith123", "Display Name": "Bob Smith", "Account Creation Date": "2016-10-10", "Following": "34", "Followers": "46", "Number of playlists": "32", "Playlist names": ["5th Dimension", "Dumb Chilling", "Rock v2 / Nu Metal", "Party \ud83c\udf7b", "Rap", "Pumping Iron", "Aggression", "Soundcloud 4", "Oldies but Goodies", "Chopped and Screwed", "Cruel Winter", "Soundcloud", "Halloween 2020", "Trap Christmas", "80's Night", "EDM", "Life of Pablo Tour", "Igor Tour", "Thugger", "Playboi Carti", "Cactus Jack", "WAKE UP MR WEST, OH HE'S UP", "Future", "Denzel", "LORDE PRETTY FLACKO JOYDE", "AstroWorld \ud83c\udfa2\ud83c\udfa1\ud83c\udfa0", "Daytona Tour", "Children of the Korn", "Rock", "Classics", "Floyd", "Chill Rock"], "Total Number of Songs Analyzed": "27334", "Data Lifecycle": "2020-01-24 19:37 to 2021-01-25 20:52"}
    
    

    and as a bonus you get escaped unicode characters.

    Reply

Leave a Comment