我正在尝试从python脚本访问JSON值。我试图访问的值是" name"只是,非常感谢我能帮助我如何使用JSON数据文件的python脚本:
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 9101083
},
"id": "9101083",
"name": "My Meat Wagon",
"url": "https://www.zomato.com/dublin/my-meat-wagon-smithfield?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "Market Square, Smithfield, Dublin Dublin 7",
"locality": "Smithfield",
"city": "Dublin",
"city_id": 91,
"latitude": "53.3489980000",
"longitude": "-6.2788120000",
"zipcode": "Dublin 7",
"country_id": 97,
"locality_verbose": "Smithfield, Dublin"
},
在我的test.py文件中
with open('data.json') as data_file:
data = json.load(data_file)
data["restaurant"]["name"]
print data
我应该怎么做让程序只获得餐馆的名称?
答案 0 :(得分:2)
简单地写data["restaurant"]["name"]
不会做对字典有意义的任何事情,它只是查找它,返回值然后不做任何事情。特别是,它不会改变data
所指的内容。如果你想要,你必须写:
data = data["restaurant"]["name"]
我不建议这样做,因为你失去了访问json结构中任何其他内容的能力。相反,只需打印值:
print data["restaurant"]["name"]