【问题标题】:On the generation of a good JSON string in Python在 Python 中生成一个好的 JSON 字符串
【发布时间】:2014-10-28 20:59:39
【问题描述】:

我的系统由一个 C++ 主要部分组成,它充当复杂过程的核心。该核心负责执行执行多项任务的 python 脚本,然后在基于 HTML 技术的图形用户界面上显示这些脚本。这个 HTML 文档是使用 WTL 加载的,但它并不相关,因为我的问题是在 python 上生成的信息到达那个点之前出现的。

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)

然后我使用适当的 API 调用将此信息发送到 C++: API_Call 是执行并返回 python 生成的字符串的方法。

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

如果我执行这些行,我会得到奇怪的字符和损坏的数据,而如果我用 python 中的原始代码代替:

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..."

它工作得很好,所以我敢说问题可能出在 json.JSONEncoder() 上,或者可能是 json.JSONEncoder 和 PyString_AsString() 中的编码问题。

有什么想法吗?

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

为了解决这个问题,我一直在尝试一些想法。

  • 最令人震惊的是:如果我只是从调试控制台复制编码字符串,将其粘贴到虚拟字符串中,然后返回该字符串,一切正常!但显然我确实需要 json.JSONEncoder 的输出。

【问题讨论】:

  • 您是否尝试过在 Python 代码中记录 json_str(或 my_python_dict)?
  • 是的,我做到了。我什至尝试从 python 控制台打印 json_string 并将虚拟测试字符串替换为控制台中的输出,并且效果很好。
  • 试试这个github.com/simplejson/simplejson 看看是否有区别。还要检查stackoverflow.com/questions/1446347/…
  • 什么时候检查c_str的内容?当您使用json.JSONEncoder().encode() 的结果时,是否有可能在您使用c_str 之前,Python 对象已被释放或以其他方式修改?
  • 什么是“奇怪的字符和损坏的数据”?给我们一个小例子 dict,当你从 Python 记录它时 JSON 的样子,以及你在 C 代码中得到的字节是什么。

标签: python c++ json python-2.7 python-c-api


【解决方案1】:

将评论转换为答案...

你什么时候检查c_str的内容?在使用c_str 的内容之前,请确保json.JSONEncoder().encode() 创建的Python 字符串对象没有被释放或以其他方式修改。

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2011-04-29
    • 1970-01-01
    • 2011-10-22
    • 2016-03-17
    • 2011-09-16
    • 1970-01-01
    • 2014-05-23
    • 2011-09-24
    相关资源
    最近更新 更多