【发布时间】:2013-02-27 21:25:25
【问题描述】:
我正在尝试使用 Python 的 simplejson 加载一些地理数据。
<!-- language: lang-py -->
string = file("prCounties.txt","r").read().decode('utf-8')
d = simplejson.loads(string)
文本文件有一个波浪号,单词应该是 Añasco 而不是 SimpleJson 不解析的 u"A\xf1asco"。来源是geoJson file from github
{"type": "FeatureCollection", "properties": {"kind": "state", "state": "PR"}, "features": [[{"geometry": {"type": "MultiPolygon", "coordinates": [[[[-67.122, 18.3239], [-67.0508, 18.3075], [-67.0398, 18.291], [-67.0837, 18.2527], [-67.122, 18.2417], [-67.1603, 18.2746], [-67.1877, 18.2691], [-67.2261, 18.2965], [-67.1822, 18.3129], [-67.1275, 18.3184]]]]}, "type": "Feature", "properties": {"kind": "county", "name": u"A\xf1asco", "state": "PR"}}]]}
Python 给了我错误simplejson.decoder.JSONDecodeError: Expecting object
我用来从 GitHub 加载生成prCounties.txt 的脚本。变量counties 是与相关 GEOjson 数据的位置相关的字符串列表。
很明显,这不是保存这些数据的正确方法:
<!-- language: lang-py -->
countyGeo = [ ]
for x in counties:
d = simplejson.loads(urllib.urlopen("https://raw.github.com/johan/world.geo.json/master/countries/USA/PR/%s" % (x)).read())
countyGeo += [ d["features"][0]]
d["features"][0]=countyGeo
file("prCounties.txt", "w").write(str(d))
编辑:在最后一行,我将str 替换为simplejson.dumps。我猜它现在可以正确编码。
file("prCounties.txt", "w").write(simplejson.dumps(d))
【问题讨论】:
-
u"A\xf1asco"与u"Añasco"(和u"A\u00f1asco")相同。 -
您将其视为
u"A\xf1asco"的原因是(在Python 2.x 中),unicode 字符串的repr会转义任何非ASCII 字符。例如,在您的交互式解释器中,u'ñ'将打印出u'\xf1',但print u'ñ'将打印出ñ。 -
还有其他原因
simplejson没有正确加载吗? -
是的,因为您的字符串不是 JSON
object,而是dict的 Pythonrepr。它们通常非常相似,但它们不是一回事,你不能对它们一视同仁。特别是,您不能在 JSON 对象中包含u"Añasco";您需要在普通双引号中使用 UTF-8 字符串文字。 -
好的,这正是我所怀疑的:您在每个文件上调用
loads,然后写下其中的str,然后尝试在str上调用loads。当然,这是行不通的。如果您只使用dumps而不是str,您可以稍后将其加载回来。或者只保留 JSON 字符串,并将名称映射到 JSON 字符串而不是对象。或者……真的,如果你只是想清楚你想要做什么,应该很容易想到有明显反向操作的东西,然后去做。
标签: python json internationalization simplejson