2

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

enter image description here

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)
3
  • 2
    The json documentation shows examples to encode and decode json, i.e. going from json to string and vice versa Commented Sep 19, 2017 at 13:20
  • Printing the value of message given to json.loads() will be very helpful. Commented Sep 19, 2017 at 13:37
  • You should really try to print it from within the function. It seems you are calling it with an empty string value for message. For example, json.loads('') gives a very similar error in my installation. Commented Sep 19, 2017 at 14:07

4 Answers 4

1

You should use the json Python package. To have a JSON, you could simply do import json and json.dumps(message).

Sign up to request clarification or add additional context in comments.

1 Comment

I tried, but it did not work, I updated the question with the error.
1

Use a Json package in python

import json
data = json.loads(your_var)

In data variable you get a json format data

hope this will help you

1 Comment

I tried, but it did not work, I updated the question with the error.
1

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) 

4 Comments

I tried, but it did not work, I updated the question with the error.
can you print the value of message?
I could, and It gives me the message formatted as I send it. But I don't know how to re-parse it again into JSON
if you could show, it may be easier to spot the issue. Maybe it is some custom formatting or whitespace or something silly like that.
0

I tried this way and it worked for me, I converted the message into a dictionary using ast and then used the new message as I wanted:

    formattedMessage = ast.literal_eval(format(message))
    self.write_message(formattedMessage["name"])

1 Comment

If the source is a json text, this is going to produce very fragile code. I would rather make sure that a proper JSON parser works. simplejson is known to produce more informative error messages, if that helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.