4

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)

1 Answer 1

10

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'ÖÄÜ'
4
  • this throws an error : f.write(unicode(inputFeatures_json, "UTF-8")) TypeError: decoding Unicode is not supported
    – Smalis
    Commented Mar 24, 2015 at 13:34
  • 1
    try f.write(inputFeatures_json.encode("UTF-8")) if you write it into a file take a look at stackoverflow.com/questions/5483423/…
    – Martin
    Commented Mar 24, 2015 at 13:38
  • take a look at: stackoverflow.com/a/9942822/1914034 Commented Mar 24, 2015 at 13:48
  • 1
    f.write(inputFeatures_json.encode("UTF-8")) worked. So my code is now : 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')) f.close
    – Smalis
    Commented Mar 24, 2015 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.