EN
JavaScript - deserialize json to object
8 points
In JavaScript, it is possible to deserialize (parse/convert) objects to JSON in the following ways.
xxxxxxxxxx
1
var studentJson = '{"name":"John","age":25,"todos":["Sleeping","Lectures","Classes","Shopping"]}';
2
var studentObject = JSON.parse(studentJson);
3
4
console.log('Name: ' + studentObject.name);
5
console.log('Age: ' + studentObject.age);
6
7
console.log('TODOs:');
8
9
for (const entry of studentObject.todos) {
10
console.log('+ ' + entry);
11
}
Note:
JSON.parse
method has been introduced in ES5.
xxxxxxxxxx
1
function parseJson(json) {
2
let object = null;
3
let result = eval( 'object = (' + json + ')' );
4
5
return object || result;
6
}
7
8
9
var studentJson = '{"name":"John","age":25,"todos":["Sleeping","Lectures","Classes","Shopping"]}';
10
var studentObject = parseJson(studentJson);
11
12
console.log('Name: ' + studentObject.name);
13
console.log('Age: ' + studentObject.age);
14
15
console.log('TODOs:');
16
17
for (const entry of studentObject.todos) {
18
console.log('+ ' + entry);
19
}
Note: this approach is not recommended if
JSON.parse
method is available because of security - eval parse and execute all source code - can be dangerous if comes from outside.