【问题标题】:JSON to dictionary in JavaScript?JSON到JavaScript中的字典?
【发布时间】:2013-07-04 00:10:24
【问题描述】:

在我的 JS 代码中,我需要将来自服务器的 JSON 响应转换为字典,以便我可以通过键名访问它们。情况如下:

说,这是来自我服务器的 JSON 响应:

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

现在我需要创建一个字典变量,其中键是 id,值是(比如说)名称,以便我可以访问它们 variable.id 或 variable[id_value](来自循环)。

如何做到这一点?非常感谢您的帮助。

谢谢 维韦克·拉古纳坦

【问题讨论】:

    标签: javascript type-conversion


    【解决方案1】:

    您可以编写一个 javascript 函数,通过 id 从员工列表中获取员工:

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

    然后在将 JSON 字符串解析回 javascript 对象后,对从服务器获得的响应使用此函数:

    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);
    }
    

    【讨论】:

      【解决方案2】:

      请注意,这不是有效的 JSON:您必须使用双引号,而不是单引号。

      假设您已修复该问题,并且 JSON 已被检索到字符串变量 jsonResult,您需要使用 JSON.parse() 对其进行解析以获取对象:

      var result = JSON.parse(jsonResult);
      

      您可以从那里构建字典:

      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"
      

      您说“并且值是(说)名称” - 如果您不需要 department 值,那么在上面的 for 循环中说 employees[ emp.id ] = emp.name; 然后(显然)employees[56] 会给你“哈利”直接。

      演示:http://jsfiddle.net/RnmFn/1/

      【讨论】:

        【解决方案3】:

        好吧,假设 JSON 已经被解析为 Object

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

        您可以遍历data.employees 来构建“字典”(Object):

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

        然后,给定一个employeeId

        var employee = employees[employeeId];
        

        【讨论】:

          【解决方案4】:

          这样的东西可以让你在一行中创建一个字典,并指定使用的键和值,或者至少是值成为整个对象的键。

          function toDictionary(items, key, value) {
          
              var dictionary = {};
          
              if (items) {
                  for (var i = 0; i < items.length; i++) {
                      var item = items[i];
                      dictionary[key(item)] = value ? value(item) : item;
                  }
              }
          
              return dictionary;
          }
          

          示例用法:

          var dictionary = toDictionary(result.employees, function (record) { return record.id; });
          var employee = dictionary[34];
          if (employee) {
            // do something with employee object
          }
          

          【讨论】:

            猜你喜欢
            • 2018-11-06
            • 2013-04-20
            • 1970-01-01
            • 2020-07-20
            • 2019-02-03
            • 2021-11-23
            • 2018-05-31
            • 2017-06-28
            • 1970-01-01
            相关资源
            最近更新 更多