Saturday 1 September 2018

Convert string to JavaScript object

By using JSON.parse method, you can convert JSON string to JavaScript object.

object.html
<!DOCTYPE html>
<html>

<head>
    <title>Convert string to JSON object</title>
</head>

<body>
    <div id="data">

    </div>

    <script type="text/javascript">
        var str = '[{"firstName":"Hari Krishna","lastName":"Gurram","age":27},{"firstName":"Kiran Kumar","lastName":"Darsi","age":28}]';

        var employees = JSON.parse(str);

        var result = "";

        for (var i = 0; i < employees.length; i++) {
            result += ("firstName : " + employees[i].firstName + "<br />");
            result += ("lastName : " + employees[i].lastName + "<br />");
            result += ("age : " + employees[i].age + "<br /><br />");
        }

        document.getElementById("data").innerHTML = result;
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

firstName : Hari Krishna
lastName : Gurram
age : 27

firstName : Kiran Kumar
lastName : Darsi
age : 28


Previous                                                 Next                                                 Home

No comments:

Post a Comment