如果我喜欢这个
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
var UserDeserialize = new JSONAPIDeserializer('id');
UserDeserialize.deserialize({ data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] })
.then(a => console.log(a))
我能够获得所需的反序列化输出
[{id:'1'},{id:'2'}]
但是,如果我创建一个序列化数据的变量,并尝试像这样序列化相同的
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
var test = "{ data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] }"
var UserDeserialize = new JSONAPIDeserializer('id');
UserDeserialize.deserialize(test)
.then(a => console.log(a))
我这样得到错误: -
/Users/acid/node_js/node_modules/jsonapi-serializer/lib/deserializer-utils.js:70
var dest = keyForAttribute(from.attributes || {});
^
TypeError: Cannot read property 'attributes' of undefined
at extractAttributes (/Users/acid/node_js/node_modules/jsonapi-serializer/lib/deserializer-utils.js:70:36)
at module.exports.perform (/Users/acid/node_js/node_modules/jsonapi-serializer/lib/deserializer-utils.js:123:13)
at resource (/Users/acid/node_js/node_modules/jsonapi-serializer/lib/deserializer.js:26:10)
at module.exports.deserialize (/Users/acid/node_js/node_modules/jsonapi-serializer/lib/deserializer.js:39:14)
at Object.<anonymous> (/Users/acid/node_js/localhost/velekaam/serial.js:13:17)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:425:7)
at startup (bootstrap_node.js:146:9)
at bootstrap_node.js:540:3
我怎么能纠正这个?
答案 0 :(得分:0)
替换...
var test = "{ data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] }"
UserDeserialize.deserialize(test)
...与:
var test = '{"data":[{"type":"ids","id":"1"},{"type":"ids","id":"2"}]}'
UserDeserialize.deserialize(JSON.parse(test))
......或者,用:
var test = { data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] }
UserDeserialize.deserialize(test)