JavaScript eval function with JSON

This post contains a simply example of how to use the eval function in JavaScript to make a string containing JSON into an actual JavaScript object.

The example JSON was from here and below is the code.

Please note:

The parenthesis are required because of an oddity in the JavaScript syntax. I’m unsure of the reasons at the moment. It is briefly mentioned on this page.

It is probably better to use this -> http://www.json.org/json_parse.js … than to use eval though as it is a parser. Eval seems to be considered less secure though it is probably faster.

<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">

var jsonString = '{ "glossary": {"title": "example glossary", "GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';
var title = eval('(' + jsonString + ')').glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para;
alert(title);

</script>
</body>
</html>

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: