0

I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.

I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.

The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total. I expect all the elements to be assigned to the variable.

request.open('GET', 'http://localhost:3000/listofvoted', true);

request.onload = function () {
    console.log(this.response)
    console.log(JSON.parse(this.response));
}

request.send();

The JSON I receive:

{
  "name": "Bran",
  "name": "Ram",
  "name": "Sam"
}
Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Dark Programmer
  • 482
  • 3
  • 6
  • 18

1 Answers1

1

Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.

For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.

Here are some alternative ways of representing what you have that may work:

Use an array of discrete objects:

[
  { "name": "Bran" },
  { "name": "Ram" },
  { "name": "Sam }"
]

Use an array of names:

{
  "names": [ "Bran", "Ram", "Sam" ]
} 

As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.

See also, How to get the JSON with duplicate keys completely in javascript

Wyck
  • 10,311
  • 6
  • 39
  • 60