Revell Revell - 2 years ago 131
Python Question

Using json.loads in Python 2.7 returns unicode object instead of dict

I'm running into an issue with parsing JSON data into a dict which I cannot figure out.

I'm connecting to a Tornado websocket from JavaScript and sending the following data, entered into a textfield:

{"action": "something"}

The way I'm sending it to the websocket is:

sock.send( JSON.stringify( $('textfield').value ) );

Now in Python I have the following code in my WebsocketHandler::on_message():

print("Message type: " + str(type(message)) + ", content: " + message)

parsed_message = json.loads(message)

print("Parsed message type: " + str(type(parsed_message)) + ", content: " + parsed_message)

And the output from this is:

Message type: <type 'unicode'>, content: "{\"action\":\"START_QUESTION_SELF\"}"
Parsed message type: <type 'unicode'>, content: {"action":"START_QUESTION_SELF"}

Now I would expect the second printed message to be a
and I cannot figure out why this isn't working. Any help would be greatly appreciated.

Answer Source

It doesn't work because when you do sock.send(JSON.stringify('{"action": "something"}')); you send this "{\"action\": \"something\"}"

When you print message you can verify that it actually contains quotes. Hence, it is being interpreted as a string by json.loads.

Easiest solution would be invoking json.loads again:

parsed_message = json.loads(json.loads(message))

However you should really consider converting textfield value into an object and then using JSON.stringify on it. Something like this:

sock.send(JSON.stringify(JSON.parse( $('textfield').value)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download