我想使用其ID号从外部json
文件中随机选择歌曲名称和艺术家:
[
{
"id": 1,
"Song1": {
"Song_nam": "killer queen"
},
"Song_artist": "queen"
},
{
"id": 2,
"Song1": {
"Song_nam": "Africa"
},
"Song_artist": "Toro"
},
{
"id": 3,
"Song1": {
"Song_nam": "Perfect"
},
"Song_artist": "Ed sheeran"
}
]
答案 0 :(得分:1)
“ songs.json” 内容:
[
{
"id": 1,
"Song1": {
"Song_nam": "killer queen"
},
"Song_artist": "queen"
},
{
"id": 2,
"Song1": {
"Song_nam": "Africa"
},
"Song_artist": "Toro"
},
{
"id": 3,
"Song1": {
"Song_nam": "Perfect"
},
"Song_artist": "Ed sheeran"
}
]
代码:
import json
from random import choice
with open("songs.json") as f:
content = json.loads(f.read())
winner = choice(content)
print(json.dumps(winner, indent=4))
输出:
{
"id": 2,
"Song1": {
"Song_nam": "Africa"
},
"Song_artist": "Toro"
}
答案 1 :(得分:0)
使用touchCard
random.choice()