Data, Maps, Usability, and Performance

How to parse and search JSON in JavaScript

Last updated on October 22, 2012 in Development

finding or grep in JSON

My last post highlighted how you can quickly visualize JSON data with a free online JSON viewer. But, most likely, you actually want to find something in a JSON file or string programmatically. So, how do you search through JSON? How do you find an object by looking for a value or key or both? If we focus on JavaScript we have some native functions which allow us to parse JSON format (JSON.parse()) and turn JSON notation into a string (JSON.stringify()), but you still need to look through all those deeply nested objects to find what you need.

First, make sure that you are working with valid JSON. Go to an online JSON validator like JSONlint and confirm that the code is actually valid. Here is an example of a valid JSON object:

If you paste this into JSONLint and press validate, you will get a green success message. Otherwise it will throw a red error and tell you where to look. If you are working with a valid JSON string, the first thing you need to do is parse it into a JavaScript object using JSON.parse(json-string). This allows you to know loop through the JavaScript objects and find what you need.

Now, are you looking to get the objects that have a particular key in the JSON? Are you looking for an array of objects that match on a particular value? Perhaps you want both, grabbing the object that matches a key and value. The getObjects function below will allow you to retrieve all these things from your JSON string.

I have also included a getValues function that will return an array of values that match on a certain key. Finally, the getKeys function will return an array of keys that match on a certain value. Here is the code:

Related Links:

Data Binding with jQuery, JSON, and JavaScript templates

Tempo – a tiny JSON rendering engine that enables you to craft data templates in pure HTML

Convert XML to json

CSS-like selectors for JSON

JSONMate – JSON editor, inspector and beautifier

Tags: ,

Facebook Twitter Hacker News Reddit More...