我的Python脚本有问题。当我不使用以下字母时,一切正常:ą,ć,ź等。使用api发送短信的脚本。邮差工作也是如此。 Python 2.7。
我想编码为UTF-8,但我有:{"timestamp":"2018-04-25T08:04:04.418+0000","status":400,"error":"Bad Request","message":"JSON parse error: Invalid UTF-8 start byte 0x9c\n
我的剧本:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import httplib
if len(sys.argv) < 3:
print("no agrs")
print("arg1: number")
print("arg2: sender")
print("arg3 and next: message")
else:
headers = {"Content-Type": "application/json; charset=utf8",
"Authorization": 'Basic xxxx'}
conn = httplib.HTTPConnection('xxxx', 5050)
message = ""
for i in sys.argv[3:]:
message = message + " " + i
conn.request("POST", "/my/url/",
"{\"receiver\": \"" + sys.argv[1] + "\",\"sender\": \"" + str(sys.argv[2]) + "\", \"content\": \"" + str(message) + "\"}",
headers)
response = conn.getresponse()
print(response.status, response.reason)
print(response.read())
if response.status == 200:
print("sent!")
conn.close()
我的错误:
{"timestamp":"2018-04-25T08:53:25.834+0000","status":400,"error":"Bad Request","message":"JSON parse error: Invalid UTF-8 start byte 0x9c\n at [Source: (PushbackInputStream); line: 1, column: 66]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0x9c\n at [Source: (PushbackInputStream); line: 1, column: 66]\n at [Source: (PushbackInputStream); line: 1, column: 60] (through reference chain: my-method[\"content\"])","path":"path to my url"}
答案 0 :(得分:1)
使用json
模块构建JSON:
# coding=UTF-8
import sys
import json
s = sys.argv[1]
j = json.dumps({"message": s})
print j
使用它:
$ python2.7 so.py "message with characters like ąśćżźć"
输出:
{"message": "message with characters like \u0105\u015b\u0107\u017c\u017a\u0107"}