python:修复写入json文件的数据中的转义unicode字符
我的程序有问题。 我访问GooglePlacesAPI并获取json,解析它,只获取我感兴趣的值,然后将它们写入文件。我对谷歌api响应中的unicode字符有问题。 我使用的是运行在Ubuntu 17.04上的python 2.7.13 问题在于API返回的字符串为: 索菲亚艺术国家中心博物馆 有一个特殊的字符:i 但在文件中,我发现: 国家艺术中心博物馆 从请求中获取数据并使用json.loads后,我在dict中获得unicode字符串,并从那里获得转义字符。 这是我的密码:python:修复写入json文件的数据中的转义unicode字符,python,json,python-2.7,unicode,utf-8,Python,Json,Python 2.7,Unicode,Utf 8,我的程序有问题。 我访问GooglePlacesAPI并获取json,解析它,只获取我感兴趣的值,然后将它们写入文件。我对谷歌api响应中的unicode字符有问题。 我使用的是运行在Ubuntu 17.04上的python 2.7.13 问题在于API返回的字符串为: 索菲亚艺术国家中心博物馆 有一个特殊的字符:i 但在文件中,我发现: 国家艺术中心博物馆 从请求中获取数据并使用json.loads后,我在dict中获得unicode字符串,并从那里获得转义字符。 这是我的密码: #!/usr
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib2
import json
def getPlaces(category, country, city, url, token):
requestURL = url.replace("CATEGORY", category)
requestURL = requestURL.replace("CITY", city)
if not (token is None):
requestURL = requestURL + "&pagetoken=" + token
jsonData = urllib2.urlopen(requestURL).read()
data = json.loads(jsonData)
result = []
for item in data["results"]:
result.append(getRowData(item, country, category))
if "next_page_token" in data:
nextToken = data["next_page_token"]
result = result + getPlaces(category, country, city, url, nextToken)
return result
def getRowData(item, country, category):
lsit = []
name = item["name"]
lat = item["geometry"]["location"]["lat"]
lng = item["geometry"]["location"]["lng"]
return [country, category, name, lat, lng]
# def listToStr(lst):
# result = '[ '
# if lst[0] is
def_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=CATEGORY+in+CITY&key=NOKEY:)"
attractions = getPlaces("museum", "Spain", "Madrid", def_url, None)
with open('data.txt', 'w') as outfile:
json.dump(attractions, outfile)
我已经阅读了一些关于这个主题的内容和我正在使用的libs的信息,但是我无法解决这个问题。也许您可以尝试encode().decode(),因为“Sof\u00eda.encode().decode()
工作正常
在您的代码中,我将更改getRowData
函数,如下所示:
def getRowData(item, country, category):
lsit = []
name = item["name"]
lat = item["geometry"]["location"]["lat"]
lng = item["geometry"]["location"]["lng"]
return [country.encode().decode(), category.encode().decode(),
name.encode().decode(), lat, lng]
是的,我以前试过这个,但仍然得到:UnicodeEncodeError:“ascii”编解码器无法对39位的字符u'\X'进行编码:序号不在范围内(128)我使用Java和Google的gson库重写了它,但我仍然好奇如何修复此问题。:)