dsjbest2014 2013-07-22 19:27
浏览 70
已采纳

Golang JSON解组python字符串

I'm working with an AWS SQS queue where python is putting strings into the queue using boto. Most of the strings are unicode, but some are in pythons basic string type.

I'm trying to read these messages with GO and running into JSON decode errors:

JSON Decode Error: 2 invalid character 'e' looking for beginning of value

All these decode errors happen when GO encounters a messages that is not a unicode string but pythons basic string format.

Is there a way of converting python strings into unicode strings from GO? ascii -> unicode?

EDIT:

Here's an example of a working and non working json string. The only way I'm able to get the non working one is through python, GO gives the decode error above

Working:
 u'{"queue_time": "1374523279747", "object_id": "5efc90c0912fef247f028f1758082a299c018e8a2c6499289f3426217b14f0ae", "source_bucket": "ap1-cache"}',

Doesn't work:
 '{"queue_time": "1374523279.75026", "source_bucket": "eu1-cache", "object_id": "42e8b7b01ed5919a23d6d91fdc0b540944a5f45e4c387fa1c2bc20e1bf81bdeb"}',
  • 写回答

1条回答 默认 最新

  • dongpai1942 2013-07-22 20:26
    关注

    To produce proper JSON from Python, you can use the json library:

    >>> d = {"queue_time": "1374523279747", "object_id": "...", "source_bucket": "ap1-cache"}
    >>> d
    {'queue_time': '1374523279747', 'source_bucket': 'ap1-cache', 'object_id': '...'}
    
    >>> import json
    >>> print json.dumps(d)
    {"queue_time": "1374523279747", "source_bucket": "ap1-cache", "object_id": "..."}
    

    Note that the JSON output looks almost entirely similar for this simple example, but that's not necessarily true for more complicated things. E.g. tuples and unicode strings have different representations:

    >>> t = [u"Hello", ("World", "!"), u"\xa0"]
    >>> t
    [u'Hello', ('World', '!'), u'\xa0']
    >>> print json.dumps(t)
    ["Hello", ["World", "!"], "\u00a0"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧