admin管理员组

文章数量:1392088

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>

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>
Share Improve this question edited Aug 24, 2016 at 10:21 Lokesh Yadav asked Feb 18, 2012 at 7:42 Lokesh YadavLokesh Yadav 1,6025 gold badges25 silver badges50 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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>

本文标签: javascriptReading json from hidden input valueStack Overflow