首页 > 解决方案 > 上传错误:“latin-1”编解码器无法使用 JSON 数据上传对字符“\u2019”进行编码

问题描述

我正在使用 python 将一些 JSON 数据上传到应用程序 UI,但出现以下错误。

上传时出错:“latin-1”编解码器无法对位置 5735 中的字符“\u2019”进行编码:正文 ('â') 不是有效的 Latin-1。如果您想以 UTF-8 编码发送它,请使用 body.encode('utf-8')。

该程序从 sample.json 文件中获取输入,该文件包含一个特殊字符 ( ' ),这会给出错误。

价值:美国运通%?

我的代码如下所示:

def read_from_file(file_path, target_path=None):

    try:
        f = open(file_path, "r")
        data = json.load(f)
        f.close()

        if target_path:
            result_obj = []
            for obj in data:
                if target_path in obj['Key']:
                    result_obj.append(obj)
            data = result_obj

    except Exception as e:
        print ("ERROR reading file:", e, file=sys.stderr)
        exit(1)

    return data


def upload(server, token, data):

    params = {"token": token}

    for obj in data:
        try:
            payload = obj['Value']
            url = server + obj['Key']

            response = requests.put(url, data=payload, params=params)
            if response.status_code != 200:
                raise Exception("HTTP code %s on PUT %s" % (response.status_code, url))

        except Exception as e:
            print ("ERROR uploading:", e, file=sys.stderr)
            exit(1)

有人可以告诉我需要在哪里更改我的代码以在上传时包含特殊字符( ' )吗?

标签: pythonjsonpython-3.x

解决方案


推荐阅读