微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法解析从 xmlhttprequest.responseText 检索的字典 [已解决]

如何解决无法解析从 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);

解决方法

这是因为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","EDM","Life of Pablo Tour","Igor Tour","Thugger","Playboi Carti","Cactus Jack","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 字符。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。