Languages
[Edit]
EN

JavaScript - how to convert json to dictionary from server response?

3 points
Created by:
Kate_C
2860

As first it is good to read this article too.

1. Problem description

Conversion from server response:

{
   "result" : true,
   "people" : [
      { "id": 5,  "name": "John" },
      { "id": 21, "name": "Denis" },
      { "id": 59, "name": "Chris" }
   ]
}

To JavaScript people dictionary object with id as key.

2. Problem solution

// ONLINE-RUNNER:browser;

// response from server

var jsonResponse = '' +
    '{\n' +
    '   "result" : true,\n' +
    '   "people" : [\n' +
    '      { "id": 5,  "name": "John" },\n' +
    '      { "id": 21, "name": "Denis" },\n' +
    '      { "id": 59, "name": "Chris" }\n' +
    '   ]\n' +
    '}';

var objectResponse = JSON.parse(jsonResponse);

// array to dictionary conversion

var peopleArray = objectResponse.people;
var peopleDictionary = { };

for (var i = 0; i < peopleArray.length; ++i) {
    var entry = peopleArray[i];

    peopleDictionary[entry.id] = entry;
    //peopleDictionary[entry.id] = entry.name;
}

// result printing

console.log(peopleDictionary[21].id);
console.log(peopleDictionary[21].name);

See also

  1. https://dirask.com/q/javascript-deserialize-json-to-object-Ej4Oxp

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.