0

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.

0

1 Answer 1

1

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.

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

1 Comment

what you said works, so the line of code would be: rxStr = json.dumps(rx) and then I'm able to access the dictionary with keys in unicode format, such as rxDict[u'GOOG']. Seems a bit counterintuitive though, I already had a JSON string and I do json.dumps on it first, instead of json.loads?

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.