Kiran K.
Kiran K.

Reputation: 366

Transmitting JSON String from zmq (C) to Python problems

I have a C program which generates a JSON string using the Jansson library. The string is then sent over the ZMQ socket to a Python listener, which is trying to use the json library to decode the JSON string. I am having trouble with the JSON decode because I think the quote symbols are getting messed up during the transmission.

In the C, I generate the following JSON Object:

{"ticker":"GOOG"}

with the following code strcpy(jsonStrArr, "{\"ticker\":\"GOOG\"}\0");

In python, I print out what I receive with the following code: print 'Received ' + repr(rxStr) +' on Queue_B'

The printout that I'm seeing is:

Received "{u'ticker': u'GOOG'}" on Queue_B

I'm not a JSON expert, but I think the u' is messing up the json.loads() function, because a double quote is required.

I know I need to so something to the jsonStrArr variable, but not sure what?

Thanks in advance.

Upvotes: 0

Views: 1196

Answers (1)

Azeirah
Azeirah

Reputation: 6338

No, the u is not messing up anything.

u'string' indicates that it's a unicode string.

Run this in python 2

# -*- coding: utf-8 -*-

a = '؏' # It's just some arabic character I googled for, definitely not ascii
b = u'؏' 

print type(a)
>>> <type 'str'>
print type(b)
>>> <type 'unicode'>

So your json object is perfectly valid.

Note that the output of my example will be <type 'str'> for both string in python 3

Edit: Trying json.loads on the output you had in your post does indeed not work.

I found that printing the json code in python 2.7 changes {"ticker":"GOOG"} into {u'ticker': u'GOOG'}, however, that's just a representation, it's still valid json.

To properly print the json, you'll have to use the json.dumps function. So replace repr(rxStr) with json.dumps(rxStr)

import json

a = json.loads(u'{"ticker": "GOOG"}')

print a
>>> "{u'ticker': u'GOOG'}"
print json.dumps(a)
>>> {"ticker": "GOOG"}

Once again, python 3 will behave differently on printing the string, since in python 3 string are automatically unicode strings if I recall correctly.

Upvotes: 1

Related Questions