5

This is my sample javascript code is being executed in node.js

let commutertrip = new Map();
let t = {
    userId: 1,
    capacity: 4,
    commuteId: 1,
    endTime: new Date(),
    id: 1,
    status: "QUEUED",
    startTime: new Date(),
    price: 100
};
commutertrip.set(1, t);
let trip = {
    id: 2,
    poolerId: 3,
    poolerTrip: {
        capacity: 4,
        commuteId: 8,
        id: 1,
        endTime: new Date(),
        startTime: new Date(),
        status: "QUEUED",
        price: 55,
        userId: 1
    },
    commuterTrip: commutertrip,
    status: "QUEUED"
};
console.log(JSON.stringify(trip));

The output

{"id":2,"poolerId":3,"poolerTrip":{"capacity":4,"commuteId":8,"id":1,"endTime":"2016-07-27T06:59:51.773Z","startTime":"2016-07-27T06:59:51.773Z","status":"QUEUED","price":55,"userId":1},"commuterTrip":{},"status":"QUEUED"}

I didn't find how to fix this? The same javascript code works fine here Here's the node arguments node --debug-brk=33172 --nolazy --harmony bin\www

5
  • It does not because not every Map is serialisable. You must do that yourself, manually: 1. turn your map into a plain JS object 2. serialise it.
    – zerkms
    Commented Jul 27, 2016 at 7:06
  • @zerkms, What's the point in having map functionality? it's like you can never convert map into json. Instead of Maps, one has to declare their own object.
    – RaceBase
    Commented Jul 27, 2016 at 7:09
  • The point is to have a data structure that can associate a key of an arbitrary type with a value of an arbitrary type.
    – zerkms
    Commented Jul 27, 2016 at 7:11
  • @zerkms, I agree. If that's what you require in object which will be serialized, how do we solve that?
    – RaceBase
    Commented Jul 27, 2016 at 7:12
  • Then you use data structures that can be serialised. Eg: plain JS objects.
    – zerkms
    Commented Jul 27, 2016 at 7:13

1 Answer 1

1

The problem here is not with your code or even NodeJS. The main reason is that Set and Map could not be serialized at all. But as a way to serialize these you can convert them to array before:

var map = new Map([[1, 2], ['foo', 3], [[23, 43], 'bar']])
var data = { number: 23, myKey: map };

var serialized = JSON
  .stringify(data, (k, v) => (v instanceof Map) ? [...v] : v);

console.log(serialized);

Not the answer you're looking for? Browse other questions tagged or ask your own question.