<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>Crisis Averted!: Tag: jsonquery</title>
    <link>http://socket7.net</link>
    <description>Crisis Averted! A weblog by Brett Stimmerman.</description>
    <managingEditor>brettstimmerman@gmail.com (Brett Stimmerman)</managingEditor>
    <webMaster>brettstimmerman@gmail.com (Brett Stimmerman)</webMaster>
    <docs>http://backend.userland.com/rss</docs>
    <ttl>60</ttl>

  <item>
  <title>JSONQuery Redux</title>
  <link>http://socket7.net/article/jsonquery-redux</link>
  <description>
    &lt;p&gt;When I &lt;a href=&quot;http://socket7.net/article/jsonquery&quot;&gt; first mentioned JSONQuery&lt;/a&gt;, I actually posted the core functionality of a more comprehensive parser.  While I tried to keep things simple by writing queries in JavaScript, the task at the time required a tiny slice of custom syntax.  Because JSONQuery grew in size, and in order to keep things simple, I stripped out the custom bits before writing up the original post.  In hindsight, I realize the original code may be more complex than it needs to be.&lt;/p&gt;

&lt;p&gt;If JSONQuery accepts queries written in JavaScript, why should we waste time with a custom parser when JavaScript has a built-in parser, namely &lt;code&gt;eval&lt;/code&gt;?  That all depends on how you feel about &lt;code&gt;eval&lt;/code&gt;.  For example, &lt;a href=&quot;http://www.crockford.com&quot;&gt;Douglas Crockford&lt;/a&gt; famously &lt;a href=&quot;http://www.jslint.com/lint.html&quot;&gt;frowns upon &lt;code&gt;eval&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p class=&quot;last&quot;&gt;
The &lt;code&gt;eval&lt;/code&gt; function (and its relatives, &lt;code&gt;Function&lt;/code&gt;, &lt;code&gt;setTimeout&lt;/code&gt;, and &lt;code&gt;setInterval&lt;/code&gt;) provide access to the JavaScript compiler. This is sometimes useful for parsing JSON text, but in virtually all other cases it indicates the presences of extremely bad coding. The &lt;code&gt;eval&lt;/code&gt; function is the most misused feature of JavaScript.
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;JSONQuery is at its core a JavaScript parser.  Since any JSON text has presumably already been parsed and converted into an Object, what we're actually building is a general purpose Object query.  So, assuming you're comfortable with &lt;code&gt;eval&lt;/code&gt; in this context, JSONQuery evolves into Object.query and becomes even simpler.  Here is the new Object.query in action:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
Object.prototype.query = function(query) {
  var result = eval('this.' + query);
  return !!result ? result : null;
};

var json = {
  'name': 'Bob',
  'address': [{
      'street': '1234 Main St.',
      'city' : 'New York',
      'state': 'NY',
      'zip': '10101'
    },{
      'street': '5678 First St.',
      'city' : 'San Francisco',
      'state': 'CA',
      'zip': '94126'
    }]
};

json.query('address[1].zip'); // 94126
&lt;/pre&gt;

&lt;p&gt;Of course, there are still issues present in this minimalist implementation.  Are we certain &lt;code&gt;query&lt;/code&gt; is a String?  Are we certain &lt;code&gt;query&lt;/code&gt; is safe to &lt;code&gt;eval&lt;/code&gt;?   Are there other sanitizations we should perform?  What can be done about any parse errors during &lt;code&gt;eval&lt;/code&gt;?  These are basic issues that can be easily corrected before putting Object.query into the wild.&lt;/p&gt;

&lt;p&gt;These issues aside, the evolution of JSONQuery to Object.query has several benefits.  It's much easier to understand what's happening.   By its nature, &lt;code&gt;eval&lt;/code&gt; is much faster than the original parser.  Finally, it's more useful as a method present on any Object.  All of this assumes, of course, that there is a need to retrieve the value of a specific property of an object at any given depth &lt;em&gt;dynamically&lt;/em&gt;, using queries generated at &lt;em&gt;run-time&lt;/em&gt;.&lt;/p&gt;  </description>
      <category domain="http://socket7.net/tag/javascript">javascript</category>
      <category domain="http://socket7.net/tag/json">json</category>
      <category domain="http://socket7.net/tag/jsonquery">jsonquery</category>
      <category domain="http://socket7.net/tag/parser">parser</category>
      <category domain="http://socket7.net/tag/programming">programming</category>
    <comments>http://socket7.net/article/jsonquery-redux#comments</comments>
  <guid isPermaLink="true">http://socket7.net/article/jsonquery-redux</guid>
  <pubDate>Thu, 17 May 2007 23:55:45 -0700</pubDate>
</item>
  <item>
  <title>JSONQuery</title>
  <link>http://socket7.net/article/jsonquery</link>
  <description>
    &lt;p class=&quot;update&quot;&gt;&lt;strong&gt;Update:&lt;/strong&gt; It turns out this problem was more easily solved. I write about it in a follow-up post, &lt;a href=&quot;http://socket7.net/article/jsonquery-redux/&quot;&gt;JSONQuery Redux&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's assume you have a &lt;a href=&quot;http://en.wikipedia.org/wiki/Json&quot;&gt;JSON&lt;/a&gt; object with a predictable structure. Let's also assume you need a way to retrieve the value a specific field, at any given depth, &lt;em&gt;dynamically&lt;/em&gt;. That is, you don't know ahead of time exactly which field's value you need.  The query will be generated at &lt;em&gt;run time&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;JSONQuery allows you to access the value of a specific field of a JSON object by applying a query string written in JavaScript syntax.&lt;/p&gt;

&lt;p&gt;Here's a simple example of JSONQuery in action:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
var json = {
  'name': 'Bob',
  'address': [
    {
      'street': '1234 Main St.',
      'city' : 'New York',
      'state': 'NY',
      'zip': '10101'
    },
    {
      'street': '5678 First St.',
      'city' : 'San Francisco',
      'state': 'CA',
      'zip': '94126'
    }
  ]
};

var query = 'address[1].zip',
    val   = jsonQuery(json, query);

console.log(val); // 94126
&lt;/pre&gt;

&lt;p&gt;I realize at first glance it may seem silly to even go down this path.  But the need arose recently where I needed something just like this. It may still be silly, but it works damn well. If you have suggestions or improvements, please share.&lt;/p&gt;

&lt;p&gt;Full JSONQuery code:&lt;/p&gt;

&lt;pre class=&quot;prettyprint&quot;&gt;
function jsonQuery(json, query) {
  var params = query.split('.'),
      result = json;

  for (var i = 0, length = params.length; i &amp;lt; length; ++i) {
    var parts = params[i].split('['),
        index = null;

    for (var j = 0, len = parts.length; j &amp;lt; len; ++j) {
      index = parts[j].replace(/\]$/, '').replace(/'/g, '');

      if (!result || !result[index])
        return null;

      result = result[index];
    }
  }

  return result;
}
&lt;/pre&gt;  </description>
      <category domain="http://socket7.net/tag/javascript">javascript</category>
      <category domain="http://socket7.net/tag/json">json</category>
      <category domain="http://socket7.net/tag/jsonquery">jsonquery</category>
      <category domain="http://socket7.net/tag/programming">programming</category>
    <comments>http://socket7.net/article/jsonquery#comments</comments>
  <guid isPermaLink="true">http://socket7.net/article/jsonquery</guid>
  <pubDate>Tue, 03 Apr 2007 13:24:10 -0700</pubDate>
</item>

  </channel>
</rss>
<!-- 0.0181 -->