字符串索引必须是整数

时间:2015-10-23 12:01:25

标签: python python-2.7

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

  

TypeError:如果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请求

def GetScripts(urlParameters):
    result = requests.get(constURLString + "/" + str(urlParameters)).json()
    return [x for x in result if x != []]

这里是我调用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'}

2 个答案:

答案 0 :(得分:1)

事实:

  • scriptList是一个词典列表(根据您而言)
  • for item in scriptList:一次获得一个字典
  • proc = Process(target=CreateScript, args=(item))将字典传递给CreateScript函数
  • def CreateScript(scriptsToGenerate):收到字典
  • for script in scriptsToGenerate:遍历字典的
  • if script['title'] == "IT":尝试访问字典键的title索引(字符串)。

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

答案 1 :(得分:0)

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)