[英]Read JSON formatted string in Python
我在 python 中有一個簡單的 Websockets 服務器,它從 Android 應用程序客戶端接收消息,我嘗試從客戶端以 JSON 格式生成消息有效負載,但我覺得。 它僅在字符串中時才有效。 我發現的一種解決方案是保留消息字符串但使用 JSON 格式:
try {
json.put("name", "Jack");
json.put("age", "24");
message = json.toString(2);
} catch (JSONException e) {
e.printStackTrace();
}
webSocket.send(message);
受 Javascript JSON.stringify(message)
啟發
我在服務器上打印了消息,它似乎已格式化
我的問題是如何在收到它時在服務器上將其反轉回 JSON?
我在 Python 中嘗試過這種方式:
def on_message(self,message):
data = json.loads(message)
self.write_message(data['name'])
但我收到了這個錯誤:
ERROR:tornado.application:Uncaught exception in /
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tornado/websocket.py", line 494, in _run_callback
result = callback(*args, **kwargs)
File "index.py", line 24, in on_message
data = json.loads(message)
File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
您應該使用json
Python 包。 要獲得 JSON,您可以簡單地執行import json
和json.dumps(message)
。
這樣的事情對你有用嗎?
import json
# assume this is the JSON you receive
text = json.dumps(dict(name='Jack', age='24'))
# show the text to be converted
print(text)
# outputs: {"name": "Jack", "age": "24"}
# load a string and convert to Python object
# see `json` module more for details
obj = json.loads(text)
在 python 中使用 Json 包
import json
data = json.loads(your_var)
在 data 變量中你會得到一個 json 格式的數據
希望這會幫助你
我嘗試過這種方式,它對我有用,我使用ast
將消息轉換為字典,然后根據需要使用新消息:
formattedMessage = ast.literal_eval(format(message))
self.write_message(formattedMessage["name"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.