我想从python中的JSON文件中获取一个随机对象

2024-04-26 00:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,里面有一些笑话,我想得到一个随机的笑话标题和相应的笑话正文。以下是JSON的存储方式:

 {
    "body": "Now I have to say \"Leroy can you please paint the fence?\"",
    "id": "5tz52q",
    "score": 1,
    "title": "I hate how you cant even say black paint anymore"
},
{
    "body": "Pizza doesn't scream when you put it in the oven .\n\nI'm so sorry.",
    "id": "5tz4dd",
    "score": 0,
    "title": "What's the difference between a Jew in Nazi Germany and pizza ?"
},
{
    "body": "...and being there really helped me learn about American culture. So I visited a shop and as I was leaving, the Shopkeeper said \"Have a nice day!\" But I didn't so I sued him.",
    "id": "5tz319",
    "score": 0,
    "title": "I recently went to America...."
}

有什么办法吗


Tags: and文件thetoinyouidjson
2条回答

你可以把笑话列成一个单子,然后随机使用:

import random
jokes=[{
    "body": "Now I have to say \"Leroy can you please paint the fence?\"",
    "id": "5tz52q",
    "score": 1,
    "title": "I hate how you cant even say black paint anymore"
},
{
    "body": "Pizza doesn't scream when you put it in the oven .\n\nI'm so sorry.",
    "id": "5tz4dd",
    "score": 0,
    "title": "What's the difference between a Jew in Nazi Germany and pizza ?"
},
{
    "body": "...and being there really helped me learn about American culture. So I visited a shop and as I was leaving, the Shopkeeper said \"Have a nice day!\" But I didn't so I sued him.",
    "id": "5tz319",
    "score": 0,
    "title": "I recently went to America...."
}]
jokes[random.randint(0,len(jokes)]
import json

#import json file
filter = "JSON file (*.json)|*.json|All Files (*.*)|*.*||"
filename = rs.OpenFileName("Open JSON File", filter)

#Read JSON data into the datastore variable
if filename:
    with open(filename, 'r') as f:
        datastore = json.load(f)
Random.choice(datastore)

我希望它能起作用

相关问题 更多 >