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

这篇博客探讨了在Python WebSocket服务器中接收和解析来自Android客户端的JSON格式消息的问题。作者遇到一个问题,即当消息以JSON字符串发送时,服务器无法正确解析。尝试使用`json.loads()`函数时,服务器抛出了`ValueError`。解决方案可能是确保客户端发送的是有效的JSON格式,或者在服务器端进行错误处理和数据验证。
摘要由CSDN通过智能技术生成

I have a simple Websockets server in python, it receives messages from Android app clients, I tried to make the message payload from the client in JSON but I felt. It is only working when it is in String.

One solution I found is to keep the message string but with JSON format:

try {

json.put("name", "Jack");

json.put("age", "24");

message = json.toString(2);

} catch (JSONException e) {

e.printStackTrace();

}

webSocket.send(message);

Inspired by the Javascript JSON.stringify(message)

I printed the message on the server and it seems to be formatted

BQKkK.png

My question is how can I reverse back it into JSON on the server when it received?

I tried this way in Python:

def on_message(self,message):

data = json.loads(message)

self.write_message(data['name'])

but I got this error:

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)

解决方案

Will something like this work for you?

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值