Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to store and retrieve a very basic obect via JavaScript and JSON - when I run the code below, something gets put into localstorage, but when I click retrieve I just get [object Object] appended to the paragraph. Any ideas? Cheers.
<!DOCTYPE HTML>
<html>
<body>

<script>

function storeusername()
{
	var person = {};
	person.age = 25;
	person.firstname = 'Joe';
	person.lastname = 'Smith';
	localStorage.setItem('persondetails', JSON.stringify(person));
}

function getusername()
{
	document.getElementById('username').innerHTML =  JSON.parse(localStorage.getItem('persondetails'));
}


</script>
<br/>
Name: <p id="username"></p>
<input type=button value="Store" onclick="storeusername()" />
<input type=button value="Retrieve" onclick="getusername()" />
</body>
</html>
Posted

1 solution

The reason you're getting [object Object] is because JSON.parse will actually return the object you have serialized, not one of its properties.

For example, if you wish to output the username, use the following:
JavaScript
var person = JSON.parse(localStorage.getItem('persondetails'));
document.getElementById('username').innerHTML = person.firstname + person.lastname; // Or whatever the username is...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900