Python 读取 JSON 字符串 | 类型错误:字符串索引必须是整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27839195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:20:50  来源:igfitidea点击:

Reading a JSON string | TypeError: string indices must be integers

pythonjsonstringtypeerror

提问by Billy Dawson

I'm trying to create a program that will read in a JSON string through the GUI and then use this to perform additional functions, in this case breaking down a mathematical equation. At the moment I am getting the error:

我正在尝试创建一个程序,该程序将通过 GUI 读取 JSON 字符串,然后使用它来执行其他功能,在这种情况下分解数学方程式。目前我收到错误:

"TypeError: string indices must be integers"

“类型错误:字符串索引必须是整数”

and I have no idea why.

我不知道为什么。

The JSON I am trying to read in is as follows:

我试图读入的 JSON 如下:

{
"rightArgument":{
"cell":"C18",
"value":9.5,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C3",
"value":135,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C4",
"value":125,
"type":"cell"
},
"leftArgument":{
"cell":"C5",
"value":106,
"type":"cell"
},
"type":"operation",
"operator":"*"
},
"type":"operation",
"operator":"+"
},
"type":"operation",
"operator":"+"
}
import json
import tkinter
from tkinter import *

data = ""
list = []

def readText():
    mtext=""
    mtext = strJson.get()
    mlabel2 = Label(myGui,text=mtext).place(x=180,y=200)
    data = mtext

def mhello():
    _getCurrentOperator(data)

def _getCurrentOperator(data):
    if data["type"] == "operation":

        _getCurrentOperator(data["rightArgument"])        
        _getCurrentOperator(data["leftArgument"]) 
        list.append(data["operator"])
    elif data["type"] == "group":
        _getCurrentOperator(data["argument"]) 
    elif data["type"] == "function":
        list.append(data["name"]) # TODO do something with arguments
        for i in range(len(data["arguments"])):
            _getCurrentOperator(data["arguments"][i])
    else:
        if (data["value"]) == '':
            list.append(data["cell"])
        else:
            list.append(data["value"])

print(list)

myGui = Tk()
strJson = StringVar()


myGui.title("Simple Gui")
myGui.geometry("400x300")

label = Label(text = 'Welcome!').place(x=170,y=40)
btnStart = Button(myGui,text='Start',command=mhello).place(x=210,y=260)
btnRead = Button(myGui,text='Read text',command=readText).place(x=210,y=200)
txtEntry = Entry(myGui, textvariable=strJson).place(x=150,y=160)
btnOptions = Button(myGui, text = "Options").place(x=150,y=260)

myGui.mainloop()

采纳答案by Vincent Beltman

You are never parsing the string to a dictionary (json object). Change data = mtextto: data = json.loads(mtext)You should also add global datato the readText method

您永远不会将字符串解析为字典(json 对象)。更改data = mtext为:data = json.loads(mtext)您还应该添加global data到 readText 方法

回答by mhawke

TypeError: string indices must be integersmeans an attempt to access a location within a string using an index that is not an integer. In this case your code (line 18) is using the string "type"as an index. As this is not an integer, a TypeErrorexception is raised.

TypeError: string indices must be integers表示尝试使用非整数索引访问字符串中的位置。在这种情况下,您的代码(第 18 行)使用字符串"type"作为索引。由于这不是整数,因此TypeError会引发异常。

It seems that your code is expecting datato be a dictionary. There are (at least) 3 problems:

您的代码似乎希望data成为字典。有(至少)3个问题:

  1. You are not decoding ("loading") the JSON string. For this you should use json.loads(data)in the readText()function. This will return the dictionary that your code expects elsewhere.
  2. datais a global variable with value initialised to an empty string (""). You can not modify a global variable within a function without first declaring the variable using the globalkeyword.
  3. The code builds a list by appending successive items to it, however, that list is not used elsewhere. It is printed after the definition of _getCurrentOperator()but this is before any processing has been done, hence it is still empty at that point and []is displayed. Move print(list)to mhello()after_getCurrentOperator(). (BTW using listas a variable name is not advised as this shadows the builtin list)
  1. 您没有解码(“加载”)JSON 字符串。为此,您应该json.loads(data)readText()函数中使用。这将返回您的代码在其他地方期望的字典。
  2. data是一个全局变量,其值初始化为空字符串 ( "")。您不能在没有首先使用global关键字声明变量的情况下修改函数内的全局变量。
  3. 代码通过向列表追加连续项来构建列表,但是,该列表不会在其他地方使用。它在定义之后打印,_getCurrentOperator()但这是在任何处理完成之前,因此在该点它仍然是空的[]并被显示。移动print(list)mhello()_getCurrentOperator()。(顺便说一句list,不建议使用作为变量名,因为这会影响内置list

You can revise readText()to this:

您可以修改readText()为:

def readText():
    global data
    mtext=""
    mtext = strJson.get()
    mlabel2 = Label(myGui,text=mtext).place(x=180,y=200)
    data = json.loads(mtext)

回答by Brian Sanchez

sometimes you need to use json.loads again.. this worked for me..

有时你需要再次使用 json.loads .. 这对我有用..

jsonn_forSaleSummary_string = json.loads(forSaleSummary)  //still string
jsonn_forSaleSummary        = json.loads(jsonn_forSaleSummary_string)

finally!! json

最后!!json