Вопрос

json:

{"id":"1","name":"Smokey Mountain Ski Club","terrain_park":"Unknown","night_skiing":"Unknown","operating_status":"Unknown","latitude":52.977947,"longitude":-66.92094,"user":{"id":"7","username":"skier"},"tags":[{"id":"1","name":"Downhill"}],"ski_maps":[{"id":"902"}],"open_ski_maps":[],"created":"2008-04-13T00:11:59+00:00","regions":[{"id":"335","name":"Newfoundland and Labrador"}]}

I've done so that this data stores in a "data" variable..

I am trying to output all the data like: "key" : "value" list

for q in data:
print q + ': ' data[q]

This code outputs:

night_skiing: Unknown
name: Smokey Mountain Ski Club

Traceback (most recent call last):
TypeError: coercing to Unicode: need string or buffer, list found

I understand what's this error about but I don't know how to solve it..

So my question is how to put all the data from this array into variables?

Это было полезно?

Решение

When e.g. q == tags, your print line becomes:

print "tags" + ': ' + [{"id":"1","name":"Downhill"}]

Python is strongly typed, so you can't implicitly concatenate a (unicode) string with a list. You need to be explicit about what you want to happen, i.e. that the list (data[q]) should be converted to a string:

print q + ': ' str(data[q])

or, much better, use str.format rather than string concatenation (or the old-fashioned % formatting):

print "{0}: {1}".format(q, data[q])

Другие советы

Here you have a small example:

import json

try:
  # parse JSON string from socket
  p = json.loads(msg)
except (ValueError, KeyError, TypeError):
  logging.debug("JSON format error: " + msg.strip() )
else:
  # remote control is about controlling the model (thrust and attitude)
  com = "%d,%d,%d,%d" % (p['r'], p['p'], p['t'], p['y'])

Problem is that not all your data values are strings, and you are treating them as strings. Using a str format will convert the values to strings. Try this:

for q in data.iteritems():
    print '%s: %s' % q
import json

data = '{"id":"1","name":"Smokey Mountain Ski Club","terrain_park":"Unknown","night_skiing":"Unknown","operating_status":"Unknown","latitude":52.977947,"longitude":-66.92094,"user":{"id":"7","username":"skier"},"tags":[{"id":"1","name":"Downhill"}],"ski_maps":[{"id":"902"}],"open_ski_maps":[],"created":"2008-04-13T00:11:59+00:00","regions":[{"id":"335","name":"Newfoundland and Labrador"}]}'

dataDict = json.loads(data)

for key in dataDict.keys():
    print key + ': ' + str(dataDict[key])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top