0

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

1
  • 1
    You should probably paste some of your python code or clarify a bit more. Looking up a string key in a dictionary that contains "#" works just fine: >>> x = {"#foo":"bar"} >>> x["#foo"] 'bar'
    – whaley
    May 30, 2010 at 14:12

3 Answers 3

4

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.

1
  • 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
    May 30, 2010 at 14:35
3

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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