我试图从 json 文件导入数据,但它生成"TypeError: string indices must be integers"错误 json 文件如下所示


[
    {
        "SALE_PRICE": "$699.95"
    },
    {
     "SALE_PRICE": "$89.95"
    },
    {
    "SALE_PRICE": "$399.95"
    },
    {
    "SALE_PRICE": "$969.95"
    },
    {
    "SALE_PRICE": "$1,563.42"
    },
    {
    "SALE_PRICE": "$299.95"
    },
    {
       "SALE_PRICE": null
    },
    {
    "SALE_PRICE": "$429.95"
    },
    {
    "ORIGINAL_PRICE": null
    },
    {
    "SALE_PRICE": "$529.95"
    }
]

来自 OP 的代码对答案进行注释:

这是我使用的全部代码

from tkinter import * import json data = "" priceList = "" with open('C:RecoveryImage\data.json') as json_data: data = json.load(json_data) data = json.dumps(data, indent=1) priceList = data[0]["SALE_PRICE"] root = Tk() root.title("Price Viewer") Display = Frame(root) Display.pack() text = Label(Display, text= data) text.pack() root.mainloop()

您必须首先将字符串转换为等效的 json 结构

import json
data = json.loads(file_data)
print data[0]["SALE_PRICE"] #Will now print the value

另外,我可以看到您使用了"null".

在文件中使用"None"作为"null"的python等效物。

这是相关代码的格式化版本,带有我的注释:

from tkinter import *
import json
data = "" ### redundant statement
priceList = "" ### redundant statement
with open('C:RecoveryImage\data.json') as json_data:
    data = json.load(json_data) ### This 'data' refers to a list of dicts.
    data = json.dumps(data, indent=1) ### This statement is the culprit.
    priceList = data[0]["SALE_PRICE"] ### Expecting `data` to be a list of dicts, not a str
    root = Tk() # etc etc

该语句所做的只是生成原始json_data的(希望(语法相同的副本,而不是使用它。不幸的是,它也会导致data引用该冗余信息。

要么删除罪魁祸首行,要么让它以 json_data_2 = 开头而不是data =

最新更新