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
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.
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.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With