JSON文件存在问题

时间:2015-12-30 00:38:03

标签: python json string list variables

我制作的代码是从JSON文件中随机挑选信息并将其放入Applecript显示通知中。并且可以通过终端

运行

我想在我的JSON文件中创建三个不同的列表,所有列表都链接到那里:random_name,random_sentence,random_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"
]

1 个答案:

答案 0 :(得分:0)

这应该可以胜任。 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文件只包含一个字符串列表。这里有3个不同的列表,名为" name"," zin" &安培; "子" :

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