Lokesh Yadav Lokesh Yadav - 3 months ago 7
Javascript Question

Reading json from hidden input value

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>

Tim Tim
Answer

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>