Python:指向JSON的点数组

时间:2016-03-30 14:19:49

标签: python dlib

我是Python的新手,我从今天早上开始尝试将一个对象(我相信它是一个点数组)转换为JSON。

print "myobject type is: %s" % type(myobject)
print "myobject[0] is %s" % myobject[0]
myobjectJson = json.dumps(myobject)

结果

 myobject type is: class 'dlib.dlib.points'

 myobject[0] is (190, 254)

 Traceback (most recent call last):
  File "./face_landmark_detection.py", line 103, in <module>
    myobjectJson = json.dumps(myobject)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <dlib.dlib.points object at 0x1086db650> is not JSON serializable

所以,据我所知,这个对象不是JSON可序列化的。

我试过用:

myobjectJson = json.dumps(myobject, default=list)
myobjectJson = json.dumps(myobject, default=tuple)
myobjectJson = json.dumps(myobject, default=dict)
myobjectJson = json.dumps(myobject, default=__dict__)
myobjectJson = json.dumps(myobject, default=lambda o: o.__dict__)

但我一直得到同样的错误...... 我该怎么办?

谢谢

更新

dir myobject is: ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getstate__', '__hash__', '__init__', '__instance_size__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__safe_for_unpickling__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'extend', 'resize']
dir myobject[0] is: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getstate__', '__hash__', '__init__', '__instance_size__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__safe_for_unpickling__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']

1 个答案:

答案 0 :(得分:1)

假设myobject是元组列表:

import json
myobjectJson = json.dumps([list(x) for x in myobject])    

不是元组列表,是吗?尝试:

myobjectJson = json.dumps([list[p.x, p.y] for p in myobject])

myobjectJson = json.dumps([(p.x, p.y) for p in myobject])

在这种情况下,您将列表提供给json.dumps()并且不需要修改数据,因此无论您是创建元组列表还是列表列表,结果都应该相同。