[英]convert string array object into array object - Javascript
我有一個 flask 路線,我試圖將 pipe 一個 list_object [{}]
放入模板中。 它可以工作,但數據在前端以字符串形式出現。 如何將字符串轉換回 array_object 以便我可以用它做一些事情?
這是 flask 路線:app.py
@app.route('/vgmplayer')
def vgmplayer():
musicdata = music.query.order_by(func.random()).first()
musicimgdata = musicimages.query.filter_by(gamealbum = musicdata.gamealbum).order_by(func.random()).first()
if musicimgdata == None:
musicimgdata = "https://media.idownloadblog.com/wp-content/uploads/2018/03/Apple-Music-icon-003.jpg"
else:
musicimgdata = musicimgdata.gameart
musicobject = [{
"name": musicdata.gametrackname,
"path": musicdata.gamelink,
"img": musicimgdata,
"album": musicdata.gamealbum,
"artists": musicdata.artists,
"platform": musicdata.platform,
"year": musicdata.year,
"genre": musicdata.genre
}]
print(musicobject)
return render_template("musicplayer.html",rvgm = musicobject)
但是當我取回模板時:musicplayer.html
<script type="text/javascript">
function grvgm(){
All_song = "{{ rvgm|safe }}"
return All_song
}
</script>
它有一個字符串:
Example data:
All_song = grvgm()
"[{'name': '10 - M Stage Jungle B', 'path': 'https://vgmsite.com/soundtracks/zhuzhu-pets-quest-for-zhu-20…-nds-gamerip/ebulpznnyw/10%20-%20M%20Stage%20Jungle%20B.mp3', 'img': None, 'album': 'ZhuZhu Pets - Quest for Zhu', 'artists': None, 'platform': 'DS', 'year': '2011', 'genre': None}]"
我需要 list_dict 最后沒有 qoutes,以便 javascript 可以將其視為數組。
編輯:我忘了提到我試過:
function grvgm(){
All_song = "{{ rvgm }}"
All_song = JSON.parse(All_song)
return All_song
}
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data
事實證明,正如@Andy 指出的那樣,該字符串不是有效的 json 格式。 我不得不使用不同的方法。 我沒有使用管道將 list_dict 導入模板,而是使用 get 請求將 list_dict 導入前端,這樣我就可以用它做一些事情了。
應用程序.py
@app.route('/grvgm', methods=['GET'])
def grvgm():
musicdata = music.query.order_by(func.random()).first()
musicimgdata = musicimages.query.filter_by(gamealbum = musicdata.gamealbum).order_by(func.random()).first()
if musicimgdata == None:
musicimgdata = "https://media.idownloadblog.com/wp-content/uploads/2018/03/Apple-Music-icon-003.jpg"
else:
musicimgdata = musicimgdata.gameart
musicobject = [{
"name": musicdata.gametrackname,
"path": musicdata.gamelink,
"img": musicimgdata,
"album": musicdata.gamealbum,
"artists": musicdata.artists,
"platform": musicdata.platform,
"year": musicdata.year,
"genre": musicdata.genre
}]
print(musicobject)
musicobject = json.dumps(musicobject)
return musicobject
音樂播放器.js
async function load_track(index_no){
fetch('/grvgm')
.then(response => response.json())
.then(All_song => {
console.log(All_song)
// stuff goes here
})
您可以使用JSON.parse(string)
這會將字符串解析為 javascript 數組
這里也已經回答了問題: Convert string array to array in javascript
通過使用 JSON.parse() 方法,您可以輕松解析字符串。
例子:
JSON.parse(All_song)
// returns an array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.