James Urian
James Urian

Reputation: 127

How to send big set of JSON data from nodejs?

I'm trying to make a response that sends a big data of JSON. So JSON.stringify() seems not to work because let's say I have an object:

const student = {
  somevar: 15,
  anothervar: 21,
  setofdata: Map(15) {
    1 => {
      somevar: 31, 
      anothervar: 45
    }
    2... 15
  }
}

So what happens when I convert it to string will be like this: {'somevar': '15', 'anothervar': '21', 'setofdata': {}}

Now when I parse it back, it seems like he doesn't know all about inside the set of data. What module should I download to achieve this? I tried LJSON but it didn't work out.

Upvotes: 0

Views: 227

Answers (1)

MorKadosh
MorKadosh

Reputation: 6006

In this particular case, student contains a Map object, which is stringified to "{}".

A quick work-around would be to convert it to a flat object first:

const student = {
  somevar: 15,
  anothervar: 21,
  setofdata: new Map([[0, 'hello'], [1, 'world']])
}

const normalized = {...student, setofdata: Object.fromEntries(student.setofdata)};

console.log(JSON.stringify(normalized))

If you wish to use a more generic and profound solution, take a looke here:

How do you JSON.stringify an ES6 Map?

It suggests a way to customize the serialization, specifically for maps (can be also implemented on special js values like NaN, Infinity and others)

Upvotes: 1

Related Questions