In my JS code, I need to convert the JSON response from server to a dictionary so that I can access them by key names. Here is the situation:
Say, this is the JSON r
Note that that is not valid JSON: you have to use double-quotes, not single-quotes.
Assuming you fix that, and that the JSON has already been retrieved into a string variable jsonResult
, you need to parse that to get an object using JSON.parse():
var result = JSON.parse(jsonResult);
You can build a dictionary from there:
var employees = {};
for (var i = 0, emp; i < result.employees.length; i++) {
emp = result.employees[i];
employees[ emp.id ] = emp;
}
console.log(employees[56].name); // logs "Harry"
console.log(employees[56].department); // logs "marketing"
You said "and the value is the (say) name" - if you don't need the department
values then in the for loop above say employees[ emp.id ] = emp.name;
and then (obviously) employees[56]
would give you "Harry" directly.
Demo: http://jsfiddle.net/RnmFn/1/