在Python中读取JSON格式的字符串 [英] Read JSON formatted string in Python

查看:245
本文介绍了在Python中读取JSON格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个简单的Websockets服务器,它从Android应用程序客户端接收消息,我尝试使用JSON使来自客户端的消息有效负载,但我感到.它只有在String中时才起作用. 我发现的一种解决方案是保留消息字符串,但使用JSON格式:

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);

受Java脚本JSON.stringify(message)

我在服务器上打印了邮件,并且似乎已格式化

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

我的问题是,如何在收到服务器后将其反向转换为JSON?

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

我在Python中尝试过这种方式:

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) 

这篇关于在Python中读取JSON格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆