UnicodeEncodeError:'ascii'编解码器无法在位置3处编码字符u'\ xbf':序数不在范围内(128)

时间:2019-08-08 08:24:46

标签: python-2.7 encoding int python-unicode

运行在python 2.7的Ubuntu盒上编写的脚本时遇到错误。 似乎unicode存在一些问题,但我无法弄清楚。

我试图用UTF-8编码变量,但我什至不确定哪一个会导致错误“ str(count)”或“ tag [u'Value']。”。

DECLARE @json NVARCHAR(MAX)

SET @json='{  "InsertRecordData": {  "data": {  "AdditionalData": {  "DataObjects": {  "ObjData": {  "Name": "coll_exclude",  "Fields": {  "FieldData1": {  "Name": "agreement",  "Value": "1234"  },  "FieldData2": {  "Name": "system",  "Value": "live"  },  "FieldData3": {  "Name": "date_added",  "Value": "2019-08-01"  },  "FieldData4": {  "Name": "time_added",  "Value": "11:20"  }  }  }  }  }  }  }  }';


select [agreement], [system], [date_added], [time_added] from
(
    SELECT json_value(js.value, '$.Name') as Titles, json_value(js.value, '$.Value') as val
    FROM OPENJSON(@json,'$.InsertRecordData.data.AdditionalData.DataObjects.ObjData.Fields') as js) as SourceTb
PIVOT
(
    max(val)
    FOR Titles in ([agreement], [system], [date_added], [time_added])
) as PivotTable

错误未指定错误所在的参数。

Traceback (most recent call last):
  File "./AWS_collection_unix.py", line 105, in <module>
    main()
  File "./AWS_collection_unix.py", line 91, in main
    ec2_tags_per_region(region, text_file)
  File "./AWS_collection_unix.py", line 65, in ec2_tags_per_region
    print_ids_and_tags(instance, text_file)
  File "./AWS_collection_unix.py", line 16, in print_ids_and_tags
    text_file.write('%s. %s' % (str(count), tag[u'Value']))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbf' in position 3: ordinal not in range(128)

我该如何使其正常工作?

谢谢

1 个答案:

答案 0 :(得分:1)

“矮子”解决方案是使用-> unicode(count).encode('utf-8')扭曲计数, 什么将转换计数为utf-8编码的str。 但是最好的方法是了解count变量的编码。