Home  • Programming • JavaScript
Converting a JSON Text to a JavaScript Object
One of the most common use of JSON is to fetch JSON data from a web server (as a file or as an HttpRequest), convert the JSON data to a JavaScript object, and then it uses the data in a web page.
For simplicity, this can be demonstrated by using a string as input (instead of a file). JSON Example - Object From String Create a JavaScript string containing JSON syntax:
var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert a JSON text into a JavaScript object.
The eval() function uses the JavaScript compiler which will parse the JSON text and produce a JavaScript object. The text must be wrapped in parenthesis to avoid a syntax error
var obj = eval ("(" + txt + ")");
Use the JavaScript object in your page: Example
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
JSON Parser
The eval() function can compile and execute any JavaScript. This represents a potential security problem.
It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.
In browsers that provide native JSON support, JSON parsers are also faster.

Comments 0


Copyright © 2025. Powered by Intellect Software Ltd