我想从JSON delhi_hos文件中获取所有名称并将其存储在String中,以便播放器可以播放That String。现在,它扮演一个名字。因此,请提出一些建议。
JSON示例
[
{
"id": 1,
"name": "JW Marriott Hotel",
"country": "IN"
},
{
"id": 2,
"name": "Le Méridien Hotel",
"country": "IN"
},
{
"id": 3,
"name": "The Leela Palace Hotel",
"country": "IN"
}
]
我的代码
if "Hospital".lower() in sentence.lower():
# print("Which City?")
# print("1.Surat \n 2.Pune \n 3.Delhi")
with open("store.txt", 'a') as store:
store.truncate(0)
if element['name'].lower() in sentence.lower():
for items in delhi_hos:
name3 = items.get('name')
print(name3)
my_text = "Near is " + name3
my_obj = gTTS(text=my_text, lang=language, slow=False)
my_obj.save("welcome.mp3")
os.system("mpg123.exe welcome.mp3")
with open("store.txt", "r+") as text_file:
text_file.truncate(0)
并且我想要像这样的字符串中的JSON文件中的名称
"JW Marriott Hotel Le Méridien Hotel The Leela Palace Hotel"
并将其存储在变量中。
var = "JW Marriott Hotel Le Méridien Hotel The Leela Palace Hotel"
因此,我可以使用var作为播放器播放此字符串的输入。 我的主要问题是将所有名称都转换为该字符串。
答案 0 :(得分:1)
我希望这可以解决您的问题。如果出现任何错误,请添加适当的缩进。
import functools
obj = [
{
"id": 1,
"name": "JW Marriott Hotel",
"country": "IN"
},
{
"id": 2,
"name": "Le Méridien Hotel",
"country": "IN"
},
{
"id": 3,
"name": "The Leela Palace Hotel",
"country": "IN"
}
]
var = functools.reduce(lambda a, b : a + " " + b["name"], obj, "")
print(var)
答案 1 :(得分:1)
我不知道我是否理解你的问题。但是据我了解,您只是想对JSON中namefield的值进行字符串化。 我想知道为什么什么解决方案无法按预期工作。 我想到的最简单的解决方案是:
names = ""
for item in delhi_hos:
names += item['name']
当事情没有解决时,我建议先从小问题开始。首先添加打印,如果可行,则分配变量,然后添加if语句等!好看!