0

Ok. I understand when we are setting the data in our Local server the data must be in a string. So we use JSON.stringify to convert an object to a string. But I just don't understand why the converted string needs to be converted BACK to an object when we want to retrieve it out of the local server to print them on the page? Could anyone please explain to me what exactly JSON.parse does and WHEN we need to use it?

if (user.firstName === "") {
    displayMessage("error", "First name cannot be blank");
  } else if (user.lastName === "") {
    displayMessage("error", "Last name cannot be blank");
  } else if (user.email === "") {
    displayMessage("error", "Email cannot be blank");
  } else if (user.password === "") {
    displayMessage("error", "Password cannot be blank");
  } else {
    displayMessage("success", "Registered successfully");

    // set new submission
    localStorage.setItem("user", JSON.stringify(user));

    // get most recent submission
    var lastUser = JSON.parse(localStorage.getItem("user"));
    userFirstNameSpan.textContent = lastUser.firstName;
    userLastNameSpan.textContent = lastUser.lastName;
    userEmailSpan.textContent = lastUser.email;
    userPasswordSpan.textContent = lastUser.password;
  }
});

Min Kyung Kwon
  • 173
  • 2
  • 12
  • Does this answer your question? https://stackoverflow.com/questions/32710387/how-does-json-parse-work – PajLe Jun 08 '20 at 02:15
  • 1
    Because you want to use it as an object to access specific properties....otherwise it's just a string – charlietfl Jun 08 '20 at 02:15
  • 1
    Perhaps [*What is the difference between JSON and Object Literal Notation?*](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) will help. – RobG Jun 08 '20 at 02:16

0 Answers0