EN
JavaScript - convert json to dictionary from server response
6
points
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);