JSON to dictionary in JavaScript?

74,437

Solution 1

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/

Solution 2

Well, assuming the JSON has already been parsed to an Object:

var data = JSON.parse('{"status":"success","employees":[{},{},{}]}'); // abridged

You can loop over data.employees to build the "dictionary" (Object):

var employees = {};

for (var i = 0; i < data.employees.length; i++) {
    employees[data.employees[i].id] = data.employees[i];
}

Then, given an employeeId:

var employee = employees[employeeId];

Solution 3

You could write a javascript function to get an employee by id from a list of employees:

function getEmployee(id, employees) {
    for (var i = 0; i < employees.length; i++) {
        var employee = employees[i];
        if (employee.id === id) {
            return employee;
        }
    }

    return null;
}

and then use this function on the response you got from the server after parsing the JSON string back to a javascript object:

var json = 'the JSON string you got from the server';
var obj = JSON.parse(json);
var employees = obj.employees;
var employee = getEmployee(34, employees);
if (employee != null) {
    alert(employee.name);
}
Share:
74,437

Related videos on Youtube

Higher-Kinded Type
Author by

Higher-Kinded Type

Updated on December 12, 2020

Comments

  • Higher-Kinded Type
    Higher-Kinded Type over 3 years

    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 response from my server:

    {
       'status': 'success',
       'employees' : [
          { 'id': 12, 'name': 'Tom', 'department': 'finance' },
          { 'id': 34, 'name': 'Dick', 'department': 'admin' },
          { 'id': 56, 'name': 'Harry', 'department': 'marketing' }
       ]
    }
    

    Now what i need is to create a dictionary variable such that the key is the id and the value is the (say) name so that i can access them variable.id or variable[id_value] (from a loop).

    How can this be achieved? Your help highly appreciated.

    Thanks Vivek Ragunathan