读取JSON字符串| TypeError:字符串索引必须是整数 [英] Reading a JSON string | TypeError: string indices must be integers

查看:177
本文介绍了读取JSON字符串| TypeError:字符串索引必须是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

"TypeError:字符串索引必须为整数"

"TypeError: string indices must be integers"

我不知道为什么.

我尝试读取的JSON如下:

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

{
"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()

推荐答案

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

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

这篇关于读取JSON字符串| TypeError:字符串索引必须是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆