Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript - deserialize json to object

0 contributions
8 points

In JavaScript script it is possible to deserialize (parse / convert) object to json in following ways.

1. JSON.parse method example

// ONLINE-RUNNER:browser;

var studentJson = '{"name":"John","age":25,"todos":["Sleeping","Lectures","Classes","Shopping"]}';
var studentObject = JSON.parse(studentJson);

console.log('Name: ' + studentObject.name);
console.log('Age: ' + studentObject.age);

console.log('TODOs:');

for (const entry of studentObject.todos) {
    console.log('+ ' + entry);
}

Note: JSON.parse method has been introduced in ES5.

2. eval method example 

// ONLINE-RUNNER:browser;

function parseJson(json) {
    let object = null;
    let result = eval( 'object = (' + json + ')' );

    return object || result;
}


var studentJson = '{"name":"John","age":25,"todos":["Sleeping","Lectures","Classes","Shopping"]}';
var studentObject = parseJson(studentJson);

console.log('Name: ' + studentObject.name);
console.log('Age: ' + studentObject.age);

console.log('TODOs:');

for (const entry of studentObject.todos) {
    console.log('+ ' + entry);
}

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.

See also

  1. JavaScript - serialize object to json

Merged questions

  1.  JavaScript - how to parse object to json?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more