Search code examples
pythonjsonsimplejson

Very simple JSON decoding


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?


Solution

  • 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