繁体   English   中英

在 Python 中读取 JSON 格式的字符串

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM