سؤال

I have searched for this, but all the results I find make no sense to me and seem too complicated. I'm looking to use either the json or simplejson module to get the value of a string in my object.

string = '{"name": "Alex"}'

Basically, I want to extract the value 'Alex' out of there. What would I do to achieve this?

هل كانت مفيدة؟

المحلول

This is pretty straightforward using the json module:

>>> import json
>>> s = '{"name": "Alex"}'
>>> obj = json.loads(s)
>>> obj
{'name': 'Alex'}
>>> obj["name"]
'Alex'

If your Python is old enough that it doesn't have json, then use simplejson instead:

import simplejson as json

نصائح أخرى

Why not try reading the docs first? It's spelled out pretty clearly at http://docs.python.org/library/json.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top