首页 > 解决方案 > 无法解析从 xmlhttprequest.responseText 检索到的字典 [已解决]

问题描述

在我的程序中,我调用了我的 python 脚本以返回一个字典。完成 XMLHttpRequest 后,我​​试图在 JavaScript 中访问此字典。响应文本。字典会出现,但是我无法解析它。

例如:调用 this,responseText['Username']; 返回未定义

我尝试对 responseText 进行字符串化,然后对其进行解析,但这根本没有帮助。我究竟做错了什么?我已经被困在这太久了

要求的功能:

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脚本:

#!\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 页面/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>

输出:

{'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

解决方案:

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

标签: javascriptpythonjsonxmlhttprequest

解决方案


这是因为python用单引号表示字符串,而json需要双引号。

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

这会以正确的格式产生输出


{"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"}

作为奖励,您可以获得转义的 unicode 字符。


推荐阅读