Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On the generation of a good JSON string in Python

My system consists on a C++ main part, which acts as core for a complex process. This core is in charge of executing python scripts which perform several tasks and then displaying those on a Graphical User Interface based on HTML technology. This HTML document is loaded using WTL, but it is not that relevant since my problem arises before the information generated on python reach that point.

import json
#my_python_dict is the Python dictionary information I want to send to C++ -> Javascript.
json_str = json.JSONEncoder().encode(my_python_dict)

Then I send this information to C++ using appropriate API calls: API_Call is the method which executes and returns the string generated in python.

PyObject *json_string;
json_string = API_Call();
char * c_str;
c_str = PyString_AsString(json_string);

If I execute those lines I get weird characters and broken data, whereas if I substitute the original code in python for this:

import json
#my_python_dict is the Python dictionary information I want to send to C++ -> Javascript.
#json_str = json.JSONEncoder().encode(my_python_dict).
json_str = "This is a dummy test... of random lenght..."

It works just perfectly, so I dare to say that the problem is probably on json.JSONEncoder() or maybe a coding problem within json.JSONEncoder and PyString_AsString().

Any ideas?

====================== P.D. ====================================

I have been trying out a few ideas in order to try to solve this issue.

  • The most shocking one is this: If I copy the encoded string just from the debug console, paste it into the dummy string and then return that string, everything works fine! But I do need the output from the json.JSONEncoder obviously.
like image 242
Pablo Stark Avatar asked Dec 04 '25 19:12

Pablo Stark


1 Answers

Converted comment to an answer...

When do you inspect the contents of c_str? Be sure that the Python string object created by json.JSONEncoder().encode() has not been deallocated or otherwise modified before you use the contents of c_str.

like image 85
Warren Weckesser Avatar answered Dec 07 '25 13:12

Warren Weckesser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!