[GIS] Python encoding error in ArcPy

arcgis-10.2arcpyjsonunicodeencodeerror

I am writing a JSON file, as string input, using python, into a .json file in the file system.
However I am getting the following error sometimes and I don't know why.
Any ideas?

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in
position 1920: ordinal not in range(128)

The json file created is used as input in the "JSON To Features" geoprocessing tools and it fails.

# Script arguments
inputFeatures_json = arcpy.GetParameterAsText(0)
#write to file
jsonFileName = 'WebMap_{}.json'.format(str(uuid.uuid1()))
JSON_File = os.path.join(arcpy.env.scratchFolder, jsonFileName)
f = open(JSON_File , 'w')
f.write(inputFeatures_json)

Best Answer

The problem is that your string inputFeature_json has special characters that are not in the ascii encoding. If you have characters that are not in the english alphabet they can cause encoding errors. Try to convert the string as unicode.

for example:

# Script arguments
inputFeatures_json = arcpy.GetParameterAsText(0)
#wtite to file
jsonFileName = 'WebMap_{}.json'.format(str(uuid.uuid1()))
JSON_File = os.path.join(arcpy.env.scratchFolder, jsonFileName)
f = open(JSON_File , 'w')
f.write(inputFeatures_json.encode("UTF-8"))

If you have string with special characters as text in your srcipt add a python "magic line" at the beginning of your srcipt:

# -*- coding: utf-8 -*-
...
s = u'ÖÄÜ'
Related Question