如何在python中访问该对象?

时间:2016-02-02 22:26:11

标签: python arrays python-2.7 object

TEXT_TO_READ = """{

    "tts_type": "text",

    "tts_input": "I am Hungry"

}"""

我的旧代码:

scriptPath = os.path.abspath(__file__)
scriptPath = os.path.dirname(scriptPath)
line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = line

我正在尝试访问TEXT_TO_READ的tts_input。但我想,我犯了一个错误。有人可以帮我,怎么访问这个?

我无法读取代码的第4行并收到错误:TEXT_TO_READ [tts_input] = line AttributeError:'str'对象没有属性'tts_input'。有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

您需要将TEXT_TO_READ解析为对象。您可以使用python库 json 来实现这一目标。

import json
TEXT_TO_READ = """{"tts_type": "text","tts_input": "I am Hungry"}"""
TEXT_TO_READ = json.loads(TEXT_TO_READ)
# rest of the code
TEXT_TO_READ["tts_input"] = line

当然,如果代码中定义了TEXT_TO_READ字符串(不是从数据库中提取或其他内容,请使用修改@Deleisha建议)。 但是,如果你需要将它作为字符串,json.loads()会将其解析为一个对象。

更新

由于您在更新的问题中有另一个错误,我会更新我的回答。 在您的新代码中,您有

TEXT_TO_READ1 = json.loads(TEXT_TO_READ)

以后

TEXT_TO_READ["tts_input"] = line

您所做的是将对象保存到TEXT_TO_READ 1 并再次尝试拉出" tts_input"来自字符串的属性。请将其修改为TEXT_TO_READ1["tts_input"] = line

更新2

好的,所以,如果我正确理解你的代码,Request.add_json_parameter()应该接受STRING作为data参数。在作业TEXT_TO_READ["tts_input"] = line中,您只想更新原始字符串。之后,您应该使用json.dumps()

将其再次转换回字符串

因此,在此行之后

TEXT_TO_READ["tts_input"] = line

添加

TEXT_TO_READ = json.dumps(TEXT_TO_READ)

更新3(作为评论的答案)

你必须改变

line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = line

到这个

line = os.path.join(scriptPath, "input.txt")
TEXT_TO_READ["tts_input"] = open(line, "r").read()

以便实际读取文件的内容。

答案 1 :(得分:1)

您正在尝试访问字符串。进行以下更改

TEXT_TO_READ = {
    "tts_type": "text",
    "tts_input": "I am Hungry"
}