JSON转换导致错误:“str”对象没有“read”属性

2024-09-27 21:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试一个函数,它应该将json转换为纯文本

我检查过类似的线程,但发现最相关的是它们的实际功能中的问题。我对json或Python一点也不满意,但我想问题在于如何使用函数,而不是实际函数

我创建并尝试转换的json文件如下所示: 人物={}

person ['Name'] = {
'name': 'Name',
'adress': 'Somewhere',
'phone_no': '0700000000',
'email_id': None
}

这是我正在测试的功能:

def json_to_plaintext(json_file, attribute):
json_tmp = json.loads(json_file.read())
attr = json_tmp[attribute]  # collect attribute
txt_file = open("json_attribute.txt", "w+")
attr = str(attr)  # make string of object
txt_file.write(attr)
txt_file.close()

return txt_file

为了测试这个,我运行

plain_text.json_to_plaintext(r'C:\Desktop\Tests\test2', 'person')

“test2”是我创建的json文件,“person”是我认为的一个属性

当我运行此命令时,我得到一个错误:

json_tmp = json.loads(json_file.read())
AttributeError: 'str' object has no attribute 'read'

Tags: 文件to函数noname功能txtjson
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:45

json_file是文件名,不是文件。你需要打开文件才能读取它

也可以使用json.load()而不是json.loads()。它将从文件本身读取

def json_to_plaintext(filename, attribute):
    with open(filename) as json_file:
        json_tmp = json.load(json_file)
    attr = json_tmp[attribute]  # collect attribute
    with open("json_attribute.txt", "w+") as txt_file:
        attr = str(attr)  # make string of object
        txt_file.write(attr)

但是,您显示的文件不是正确的JSON文件。JSON文件应如下所示:

{ "person": {
    "name": "Name",
    "adress": "Somewhere",
    "phone_no": "0700000000",
    "email_id": null
    }
}

您展示的是一个Python脚本,它定义了一个名为person的变量。如果要读取并执行另一个脚本,可以使用import

相关问题 更多 >

    热门问题