【问题标题】:How to handle API responses(JSON) containing \x00 (or \u0000) in its data, and store the data in Postgres using django models?如何处理其数据中包含 \x00(或 \u0000)的 API 响应(JSON),并使用 django 模型将数据存储在 Postgres 中?
【发布时间】:2020-11-15 10:09:30
【问题描述】:

我正在进行 api 调用,并尝试使用 Django 模型将其响应存储在 Postgres 中。 这是我一直在做的事情:

response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
#handler is a object of a model
handler.api_response = response_data
handler.save()

但这曾经失败过,当我的 json 有像 'field_name': '\x00\x00\x00\x00\x00' 这样的字段时。它曾经给出以下错误:

DataError at /api/booking/reprice/
unsupported Unicode escape sequence
LINE 1: ... NULL, "api_status" = 0, "api_response" = '{"errorRe...
                                                             ^
DETAIL:  \u0000 cannot be converted to text.
CONTEXT:  JSON data, line 1: ..."hoursConfirmed": 0, "field_name":...

我尝试通过以下方法解决此问题:

response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
#handler is a object of a model
handler.api_response = json.loads(json.dumps(response_data).encode("unicode-escape").decode())
handler.save()

最初的问题就这样解决了。但最近,当我得到一个值为'field2_name': 'Hey "Whats up"' 的字段时。这件事因给出错误而失败:

json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 143 (char 142)

可能是因为 json.loads() 与值内的 " 混淆为封闭的 " 而不是转义的 "

现在,如果我在 json.loads(response.content.decode('utf-8')) 语句之后打印初始响应,它将显示字段为 \x00\x00\x00\x00\x00

但输出如下代码:

response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
print(json.dumps(response_data))

这会将字段显示为\\u0000\\u0000\\u0000\\u0000\\u0000\x00怎么改成\\u0000

我如何将此字段保存到 postgres 表中? 这是我能想到的。

json.loads(json.dumps(response_data).replace('\\u0000',''))

在保存到 postgres 之前添加此语句。

有没有更好的办法?

代码response_data = json.loads(response.content.decode('utf-8')) 错了吗?或者导致不逃避那个特定的角色?

【问题讨论】:

    标签: python python-3.x django postgresql django-models


    【解决方案1】:

    FWIW,我最近遇到了这个问题,您提出的解决方案也对我有用。我认为这可能是处理它的最简单的方法。显然是this is the only character that can't go into a Postgres JSON column

    json.loads(json.dumps(response_data).replace('\\u0000',''))
    

    【讨论】:

    • 奇怪的是 Postgres 不能处理这个字符。
    猜你喜欢
    • 1970-01-01
    • 2022-09-22
    • 2020-10-04
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2014-03-21
    相关资源
    最近更新 更多