我正在测试一个函数,它应该将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'
json_file
是文件名,不是文件。你需要打开文件才能读取它也可以使用
json.load()
而不是json.loads()
。它将从文件本身读取但是,您显示的文件不是正确的JSON文件。JSON文件应如下所示:
您展示的是一个Python脚本,它定义了一个名为
person
的变量。如果要读取并执行另一个脚本,可以使用import
相关问题 更多 >
编程相关推荐