Where to start with parsing JSON?
If I have JSON data stored in a string called 'data' (e.g. the example below) how do I access specific information (such as messages->unread
or pokes->most_recent
)?
{
"messages": {
"unread": 0,
"most_recent": 1300047276
},
"pokes": {
"unread": 0,
"most_recent": 0
},
"shares": {
"unread": 0,
"most_recent": 0
},
"friend_requests": [],
开发者_如何学JAVA "group_invites": [],
"event_invites": []
}
I'd like something like data['messages']['unread']
to work - but of course it won't when my data is stored as a string!
JSON parser is bundled with Python since 2.6: json
module. To unserialize a string, use json.loads
, e.g.
import json
data = json.loads(...)
You can also load directly from a file-like object with json.load
.
You run the string through a JSON parser to turn it into a suitable data structure for whatever language you are using (sets, arrays, strings, etc in Python) . There are a number listed near the bottom of http://json.org/ for a variety of languages.
精彩评论