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 -> … than to use eval though as it is a parser. Eval seems to be considered less secure though it is probably faster.

<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;