JSON fi问题

2024-06-25 22:41:18 发布

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

我正在编写一个代码,从一个JSON文件中随机选取信息,并将其放入applescript显示通知中。可以穿过终点站

我想在我的JSON文件中列出三个不同的列表,它们都链接到一个东西:random\u name,random\u sentence,random\u sub,而不是只有一个列表,从那个列表中选择所有单词。你知道吗

我该怎么做?我应该做一本字典吗?变量?制作其他JSON文件?你知道吗

Python文件:

#!/usr/bin/python

import json
import random
import subprocess

def randomLine():
    jsonfile = "sentences.json"
    with open(jsonfile) as data_file:
        data = json.load(data_file)

    # print len(data)
    return random.choice(data)

def executeShell(notif_string, notif_title, notif_subtitle):
    applescript = 'display notification "%s" with title "%s" subtitle "%s"' % (notif_string, notif_title, notif_subtitle)
    subprocess.call(["osascript", "-e", applescript])

def main():
    random_name = randomLine()
    random_zin = randomLine()
    random_sub = randomLine()
    executeShell(random_name, random_zin, random_sub)

if __name__ == '__main__':
    main()

JSON文件:

[
    "one",
    "two", 
    "three", 
    "four", 
    "five",
    "six"
]

Tags: 文件nameimportjson列表datatitlemain
1条回答
网友
1楼 · 发布于 2024-06-25 22:41:18

这样就可以了。json.load()返回一个字典,所以您可以在它上面运行random.choice()

import json
import random
import subprocess

jsonfile = "sentences.json"

def main():
    with open(jsonfile, "r") as file:
        # You might want to add a sanity check here, file might be malformed
        data = json.load(file)

    random_name = random.choice(data["name"])
    random_zin = random.choice(data["zin"])
    random_sub = random.choice(data["sub"])
    subprocess.call(["osascript", "-e", "display notification \
        '{0}' with title '{1}' \
        subtitle '{2}'".format(random_name, random_zin, random_sub)])

if __name__ == '__main__':
    main()

原始JSON文件只包含一个字符串列表。这里有三个不同的列表,分别是“name”、“zin”和“sub”:

{
    "name":[
        "one",
        "two",
        "three"
     ],
     "zin":[
        "four",
        "five",
        "six"
     ],
     "sub":[
        "seven",
        "eight",
        "nine"
    ]
}

相关问题 更多 >