Reputation: 1602
Trying to read JSON from hidden input value.
<html>
<body>
<input id="hdn" type="hidden" value='{"products":{"id":100001,name:"Ram"}}'>
<script type="text/javascript">
var jsonObj = document.getElementById('hdn').value;
alert(jsonObj);
alert(jsonObj.products.name);
</script>
</body>
</html>
Upvotes: 0
Views: 5481
Reputation: 3309
You need to parse it as var jsonObj = JSON.parse(document.getElementById('hdn').value)
Note, I changed the way you were storing your JSON object, by adding the quotes to the name
property. I added as both console.log and an alert... mostly because I prefer console.log, but you originally had an alert in there.
Here's the updated (working) code:
<html>
<body>
<input id="hdn" type="hidden" value='{"products":{"id":100001,"name":"Ram"}}'>
<script type="text/javascript">
var jsonObj = JSON.parse(document.getElementById('hdn').value);
console.log(jsonObj);
console.log(jsonObj.products.name);
alert(jsonObj);
alert(jsonObj.products.name);
</script>
</body>
</html>
Upvotes: 6