tags:

views:

95

answers:

3

I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below.

{ "artist":
    "similar": { 
        "artist": {
            "name": "Blah",
            "image": [{"#text":"URLHERE","size": "small"},{"#text":"URLHERE","size":"medium"},{"#text":"URLHERE","size":"large"}]
         }
     }
}

Any ideas how I can access the image urls of various different sizes?

Thanks,
Jack

+4  A: 

Python does not have any problem with # in strings used as dict keys.

>>> import json
>>> j = '{"#foo": 6}'
>>> print json.loads(j)
{u'#foo': 6}
>>> print json.loads(j)[u'#foo']
6
>>> print json.loads(j)['#foo']
6

There are, however, problems with the JSON you post. For one, it isn't valid (perhaps you're missing a couple commas?). For two, you have a JSON object with the same key "image" three times, which cannot coexist and do anything useful.

Mike Graham
Ah, your right about the JSON being wrong. I've fixed it now, any ideas how to access the url depending on the size I want?
Jack
@Jack, `def get_by_size(deserialized_json, size):` `for d in deserialized_json[u"artist"][u"similar"][u"artist"][u"image"]:` `if d[u"size"] == size:` `return d[u"#text"]` (I'd also dedent and `raise ValueError("%s not found" % size)` if I was going to do this as a function.)
Mike Graham
+3  A: 

In Javascript, these two syntaxes are equivalent:

o.foo
o['foo']

In Python they are not. The first gives you the foo attribute, the second gives you the foo key. (It's debatable whether this was a good idea or not.) In Python, you wouldn't be able to access #text as:

o.#text

because the hash will start a comment, and you'll have a syntax error.

But you want

o['#text']

in any case.

Ned Batchelder
A: 

You can get what you want from the image list with a list comprehension. Something like

desired = [x for x in images if minSize < x['size'] < maxSize]

Here, images would be the list of dicts from the inner level of you data structure.

Pierce