处理谷歌的半JSON API,它以字符串形式返回所有内容 - 甚至是数字元素。
// [
{
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "100.75"
,"l_fix" : "100.75"
,"l_cur" : "100.75"
,"s": "0"
,"ltt":"4:00PM EDT"
,"lt" : "Sep 26, 4:00PM EDT"
,"lt_dts" : "2014-09-26T16:00:01Z"
,"c" : "+2.88"
,"c_fix" : "2.88"
,"cp" : "2.94"
,"cp_fix" : "2.94"
,"ccol" : "chg"
,"pcls_fix" : "97.87"
}
]
将响应编码为dict:
uquotes = json.loads(status.text[3:])
print uquotes
我将传入的JSON结构的所有元素都作为字符串:
[{u'c': u'+2.88', u'ccol': u'chg', u'e': u'NASDAQ', u'ltt': u'4:00PM EDT', u'cp_fix': u'2.94', u'c_fix': u'2.88', u'l': u'100.75', u's': u'0', u'lt': u'Sep 26, 4:00PM EDT', u'pcls_fix': u'97.87', u't': u'AAPL', u'lt_dts': u'2014-09-26T16:00:01Z', u'l_fix': u'100.75', u'cp': u'2.94', u'id': u'22144', u'l_cur': u'100.75'}]
问题的两个部分:
如何对数字值进行编码,而不是使用以下内容对字符串进行编码:
try:
d[t.tag] = int(text)
except ValueError:
try:
d[t.tag] = float(text)
except ValueError:
d[t.tag] = text
尝试整数,返回到Float,默认为文本作为最后的手段。
如何将所有键转换为(ascii)?
答案 0 :(得分:1)
你抓住ValueError
的方法看起来很好,但你也可以让一切都浮起来;那里没有大数不适合浮点精度。
请注意,Google最有可能使用字符串,因为这些是货币值,float()
类型可能没有意义,除非您需要对大量这些字符串执行算术运算。
您的字符串是unicode
值并不重要,但您可以始终将它们明确地编码为ASCII:
try:
d[t.tag] = float(text)
except ValueError:
d[t.tag] = text.encode('ASCII')
当您将unicode
与str
值混合时,Python将隐式编码为ASCII,您可以互换地使用任何键的str
版本。
如果你想坚持仍然支持整数,用str.isdigit()
测试字符串;只有表示整数的值才会成立:
try:
d[t.tag] = int(text) if text.isdigit() else float(text)
except ValueError:
d[t.tag] = text.encode('ASCII')
你可以将它封装在一个函数中,然后在字典理解组合的列表理解中使用该函数:
def convert(v):
try:
return int(v) if v.isdigit() else float(v)
except ValueError:
return v.encode('ASCII')
uquotes = [{k: convert(v) for k, v in d.items()} for d in json.loads(status.text[3:])]