Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Say I get this line of JSON

[{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]

How can I convert those separate values to strings? So I can say

Print Status

And it returns

active
share|improve this question

3 Answers

up vote 4 down vote accepted

That is NOT a "line of JSON" as received from an external source. It looks like the result of json.loads(external_JSON_string). Also Print Status won't work; you mean print status.

>>> result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]
>>> print result[0]['status']
active

This is what a "line of JSON" looks like:

>>> import json
>>> json.dumps(result)
'[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]'
>>>

EDIT: If using Python 2.5, use import simplejson as json instead of import json. Make your code a bit more future-proof by doing this:

try:
    import json
except ImportError:
    import simplejson as json
share|improve this answer

First of all, that ain't JSON as was already pointed out - it's python already.

I think you want the keys of the dict automatically transform into local variables. This would be a really bad idea, although in theory, it's possible using locals ():

result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]
for k, v in result[0].items():
    locals() [k] = v
print status # prints active

Some problems:

  • Your keys might overwrite some existing local variables
  • Keys might be unicode, how would you access the variable names?

Also, as stated in the python docs, locals () should not be modified.

In short: do it like this:

print result[0]['status']
share|improve this answer
import simplejson
_dict = simplejson.loads(json_data)
for entry in _dict:
# loop over list
    print entry.get('status','Failure')
    # Find key in dict/entry
share|improve this answer
I get this error: File "/Library/Python/2.5/site-packages/simplejson/__init__.py", line 385, in loads return _default_decoder.decode(s) File "/Library/Python/2.5/site-packages/simplejson/decoder.py", line 402, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer – JCBK Apr 10 '11 at 21:06
-1 The "json_data" is the RESULT of [simple]json.loads – John Machin Apr 10 '11 at 22:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.