我只需要最后一个数字25,所以我可以将它改为int()。我有这个文本文件:
{
"members": [
{"name": "John", "location": "QC", "age": 25},
{"name": "Jesse", "location": "PQ", "age": 24},
}
然后返回年龄
的值这是我到目前为止所尝试过的,所以我很困惑......我用什么样的函数来解析它?这就是你所说的吗?我是编程和python的新手。
import json
import pprint
my_data = json.loads(open("team.json.txt").read())
print 'members whose location is in PQ'
member_in_pq = [member for member in my_data['members'] \
if member['location'] == 'PQ']
pprint.pprint(member_in_pq)
顺便说一句,我尝试了这段代码,但却出错了:
result = my_data.split(':')[-1]
答案 0 :(得分:1)
我不确定你问的是怎么做,但会尝试猜测。
首先,您显示的文本不是有效的JSON,需要更改为以下内容:
{
"members": [
{"name": "John", "location": "QC", "age": 25},
{"name": "Jesse", "location": "PQ", "age": 24}
]
}
这里可以打印出位置PQ
中每位成员的所有数据:
import json
import pprint
my_data = json.loads(open("team.json.txt").read())
members_in_pq = [member for member in my_data['members']
if member['location'] == 'PQ']
print 'members whose location is in PQ'
for member in members_in_pq:
print ' name: {name}, location: {location}, age: {age}'.format(**member)
输出:
members whose location is in PQ
name: Jesse, location: PQ, age: 24