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.
Conversion from server response:
xxxxxxxxxx
1
{
2
"result" : true,
3
"people" : [
4
{ "id": 5, "name": "John" },
5
{ "id": 21, "name": "Denis" },
6
{ "id": 59, "name": "Chris" }
7
]
8
}
To JavaScript people
dictionary object with id
as key.
xxxxxxxxxx
1
// response from server
2
3
var jsonResponse = '' +
4
'{\n' +
5
' "result" : true,\n' +
6
' "people" : [\n' +
7
' { "id": 5, "name": "John" },\n' +
8
' { "id": 21, "name": "Denis" },\n' +
9
' { "id": 59, "name": "Chris" }\n' +
10
' ]\n' +
11
'}';
12
13
var objectResponse = JSON.parse(jsonResponse);
14
15
// array to dictionary conversion
16
17
var peopleArray = objectResponse.people;
18
var peopleDictionary = { };
19
20
for (var i = 0; i < peopleArray.length; ++i) {
21
var entry = peopleArray[i];
22
23
peopleDictionary[entry.id] = entry;
24
//peopleDictionary[entry.id] = entry.name;
25
}
26
27
// result printing
28
29
console.log(peopleDictionary[21].id);
30
console.log(peopleDictionary[21].name);