Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to dictionary in JavaScript?

Tags:

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

like image 565
Higher-Kinded Type Avatar asked Jul 05 '13 20:07

Higher-Kinded Type


People also ask

Can JSON be a dictionary?

JSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists. Here is a simple example with just 4 attribute/value pairs.

What is JSON Stringify in JavaScript?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Which method converts JSON data to a JavaScript object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

How do I convert a JSON file to an object?

Convert JSON String to JavaScript Object The JSON module offers two methods - stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.


1 Answers

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/

like image 61
nnnnnn Avatar answered Oct 02 '22 12:10

nnnnnn