字符串索引必须为整数

2024-06-28 20:46:23 发布

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

我尝试在python中访问JSON对象/字典,但是得到错误:

TypeError: string indices must be integers if script['title'] == "IT":

这是我尝试在字典中访问特定键的代码:

def CreateScript(scriptsToGenerate):
    start = time.clock()
    apiLocation = ""
    saveFile = ""
    for script in scriptsToGenerate:
        print script
        if script['title'] == "IT":
            time = script['timeInterval']
            baseItem = "" 

而scriptsToGenerate是使用这个函数传入的,它向我的API发出一个HTTP请求

^{pr2}$

这就是我称之为CreateScript的地方

def RunInThread(ID):
    startedProcesses = list()
    Scripts = []
    Scripts = GetScripts(ID)

    scriptList = ThreadChunk(Scripts, 2) 

    for item in scriptList: 
        proc = Process(target=CreateScript, args=(item))
        startedProcesses.append(proc)
        proc.start()

    #we must wait for the processes to finish before continuing
    for process in startedProcesses:
        process.join()
        print "finished"

我把这个传给CreateScript

这是我的脚本对象的输出

{u'timeInterval': u'1800', u'title': u'IT', u'attribute' : 'hello'}

Tags: 对象inforif字典titledefscripts
2条回答

事实:

  • scriptList是一个字典列表(根据您)
  • for item in scriptList:一次获取一个字典
  • proc = Process(target=CreateScript, args=(item))将字典传递给CreateScript函数
  • def CreateScript(scriptsToGenerate):接收字典
  • for script in scriptsToGenerate:迭代字典的。在
  • ^{cd7>{a key}的索引{cd7>尝试访问。在

所以不,这行不通。在某个时刻,您迭代一个列表。您可能希望将脚本列表传递给CreateScript函数,因此不应该迭代scriptList。在

John,我的意思是你有一个json对象,它需要这样处理。我想你的意思是你能做下面的事吗?在

def CreateScript(scriptsToGenerate):
    #start = time.clock()
    apiLocation = ""
    saveFile = ""
    i = json.loads(scriptsToGenerate)
    if i['title'] == "IT":
        time = i['timeInterval']
        baseItem = ""

        print i['title'], i['timeInterval']

p = json.dumps({u'timeInterval': u'1800', u'title': u'IT', u'attribute' : 'hello'})

CreateScript(p)

相关问题 更多 >