简体   繁体   English

获取 JSON 的 str 表示以像 print() 一样进行编码

[英]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.

相关问题 打印str的转义表示 - Print escaped representation of a str 如何使用 _str_method 打印 myFirstCar 的字符串表示形式? - How to print a string representation of myFirstCar using the _str_method? 像__str__这样的特殊方法,它返回一个对象的数字表示 - Special method like __str__ that returns a number representation of an object 获取Django模型的JSON表示 - Get JSON representation of Django model TypeError:需要一个类似字节的对象,而不是&#39;str&#39;:即使使用编码 - TypeError: a bytes-like object is required, not 'str': even with the encode 在 Python 中使用 JSON 打印 str 和 int - print str and int without “( ' ,” in Python with JSON 需要类似字节的 object,而不是“str” JSON 文件作为 STR 打开 - a bytes-like object is required, not 'str' JSON File opened as STR 如何在JSON中获取PrimaryKeyRelatedField的字符串表示形式 - How to get string representation of PrimaryKeyRelatedField in JSON 当我写“dir”时我收到此错误TypeError:描述符&#39;encode&#39;需要&#39;str&#39;,原因是“if len(str.encode(cmd))&gt; 0 - When I write “dir” I get this error TypeError: descriptor 'encode' requires a 'str' and the reason is "if len(str.encode(cmd)) > 0 URL打开,解码编码错误TypeError:需要类似字节的对象,而不是&#39;str&#39; - URL open , decode encode error TypeError: a bytes-like object is required, not 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM