Languages
[Edit]
EN

JavaScript - convert json to dictionary from server response

6 points
Created by:
Aaron1
568

In this article, we would like to show you how to convert JSON to dictionary from server response in JavaScript.

Note: As an introduction, it is good to read this article.

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

Alternative titles

  1. JavaScript - how to convert json to dictionary from server response?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - JSON

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join