如何使用python从json获取数据

时间:2014-05-15 15:44:00

标签: python arrays json

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"}]}

我已经这样做了,这个数据存储在“数据”变量..

我正在尝试输出所有数据,例如:“key”:“value”list

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

此代码输出:

night_skiing: Unknown
name: Smokey Mountain Ski Club

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

我明白这个错误是什么,但我不知道如何解决它..

所以我的问题是如何将这个数组中的所有数据都放入变量中?

4 个答案:

答案 0 :(得分:1)

例如q == tags,您的print行变为:

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

Python是强类型的,因此您无法将(unicode)字符串与列表进行隐式连接。您需要明确说明您想要发生的事情,即列表(data[q])应该转换为字符串:

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

或更好的是,使用str.format而不是字符串连接(或旧式%格式化):

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

答案 1 :(得分:0)

这里有一个小例子:

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'])

答案 2 :(得分:0)

问题是并非所有数据值都是字符串,而是将它们视为字符串。 使用str格式会将值转换为字符串。试试这个:

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

答案 3 :(得分:0)

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])