在javascript中序列化“没有冒号符号的对象”而不会丢失内部函数
我有来自API的响应,看起来像JSON,但事实并非如此。
[ { detection:
FaceDetection {
_imageDims: [Dimensions],
_score: 0.8957952857017517,
_classScore: 0.8957952857017517,
_className: '',
_box: [Box] },
landmarks:
FaceLandmarks68 { _imgDims: [Dimensions], _shift: [Point], _positions: [Array] },
unshiftedLandmarks:
FaceLandmarks68 { _imgDims: [Dimensions], _shift: [Point], _positions: [Array] },
alignedRect:
FaceDetection {
_imageDims: [Dimensions],
_score: 0.8957952857017517,
_classScore: 0.8957952857017517,
_className: '',
_box: [Box] },
descriptor:
Float32Array [
-0.1426914483308792,
0.08866042643785477,
]
正如您所看到的,面部检测不是键值对而是功能。 (这可以从这里理解:No colon after property name in object declaration, is it valid?)。但是当我尝试序列化它时,它将避免这些功能,只采用键值对。那么我该如何序列化它而不会丢失任何东西呢?
到目前为止我尝试的是JSON.stringify(),它显然不起作用。其他是NPM包
那么如何在不丢失函数的情况下序列化这个对象呢?
回答如下:如果您控制该API端点,则不要这样做。如果你不这样做,那么也许你应该问谁想出这个,它们是如何被使用的(肯定应该有可以/知道如何使用这种格式的工具)。如果你不能做任何一个,那么API响应就是字符串,把它作为一个整体,保留格式并保存它你喜欢(文件,数据库等)。