Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

json - getting the value from text file after the colon or before the colon in python

I only need the last number 25 so i can change it to int(). I have this text file:

{
  "members": [
    {"name": "John", "location": "QC", "age": 25},
    {"name": "Jesse", "location": "PQ", "age": 24},
}

then return the value of the age

This what I have tried so far, so I am so stuck... What kind of function do I use to parse it? Is that what you call it? I'm new to programming and in 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)

By the way I tried this code but it gives an error:

result = my_data.split(':')[-1]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure what you're asking how to do, but will make an attempt to guess.

First of all, the text you show isn't valid JSON and would need to be changed to something like this:

{                                                  
  "members": [                                     
    {"name": "John", "location": "QC", "age": 25}, 
    {"name": "Jesse", "location": "PQ", "age": 24}
  ]
}                                                  

Here's something that would print out all the data for each member in location 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)

Output:

members whose location is in PQ
  name: Jesse, location: PQ, age: 24

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...