[英]Get str representation of JSON to encode like print()
I need to pass a JSON object that looks like below to a REST API (plz note the escaped " in the value - which is json in string format)我需要将如下所示的 JSON 对象传递给 REST API(请注意值中的转义 " - 字符串格式的 json)
{ "data": "{\"positionname\": \"API User\",\"person\": \"Paul\",}" }
In POSTMAN, using POST method to API endpoint with JSON above, I get 200 and a record created.在 POSTMAN 中,使用上面的 JSON 对 API 端点使用 POST 方法,我得到 200 并创建了一条记录。 When I try to do the same from Python Shell using 'requests', it fails:
当我尝试使用“请求”从 Python Shell 执行相同操作时,它失败了:
# JSON as string with proper escape
>>> data = '{"data": "{\\"positionname\\": \\"API User\\", \\"person\\": \\"Paul\\"}"}'
# Loads output removes backslashes
>>> json.loads(data)
{'data': '{"positionname": "API User", "person": "Paul"}'}
# Print output shows data -exactly- as I need to pass it to the API
# The string that print() provides is in the EXACT format that the API requires
# It needs " around data, and the escape \ character is needed.
>>> print (data)
{"data": "{\"positionname\": \"API User\", \"person\": \"Paul\"}"}
# Data still in original format...
>>> data
'{"data": "{\\"positionname\\": \\"API User\\", \\"person\\": \\"Paul\\"}"}'
# Try to pass the data to the API..
>>> response = apiRequest.post('http://apiURL/board/Input', data)
# It fails...
>>> response<Response [400]>
>>>
You don't need to "trap" the output of print()
;您不需要“捕获”
print()
的输出; you already have the data.你已经有了数据。
print()
prints the actual data as it really exists , which is distinct from the repr()
esentation of that data encoded in Python syntax. print()
打印实际数据,因为它确实存在,这与用 Python 语法编码的数据的repr()
esentation 不同。
Similarly, a call like file.write(yourdata)
or socket.send(yourdata)
will send that literal data, not the Python representation thereof.类似地,像
file.write(yourdata)
或socket.send(yourdata)
这样的调用将发送文字数据,而不是其 Python 表示。
If it's in your control, the logic you use to generate your string should look like this:如果它在您的控制之下,则您用来生成字符串的逻辑应如下所示:
content = { "positionname": "API User", "person": "Paul" }
wrapper = { "data": json.dumps(content) }
wrapper_json = json.dumps(wrapper)
...if you print(wrapper_json)
, you'll see something formatted in exactly the right way to send to your service. ...如果你
print(wrapper_json)
,你会看到一些以完全正确的方式发送到你的服务的格式。
Your use case looks strange, but if you don't find any satisfactory solution you can try this to get desired output.您的用例看起来很奇怪,但是如果您没有找到任何令人满意的解决方案,您可以尝试此操作以获得所需的输出。
data = '{ "data": "{\\"positionname\\": \\"API User\\",\\"person\\": \\"Paul\\",}" }'
dataSplitted = data.split("\\")
output = ""
for word in dataSplitted:
output = "{}\{}".format(output, word)
output = output[1:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.