What is json-query?
The json-query npm package allows you to query and manipulate JSON data using a simple and intuitive syntax. It is particularly useful for extracting specific data from complex JSON structures.
What are json-query's main functionalities?
Basic Querying
This feature allows you to perform basic queries on JSON data. In this example, it filters the 'people' array to find entries where the 'country' is 'NZ'.
const jsonQuery = require('json-query');
const data = { people: [{ name: 'Matt', country: 'NZ' }, { name: 'Pete', country: 'AU' }] };
const result = jsonQuery('people[country=NZ]', { data: data }).value;
console.log(result); // Output: [{ name: 'Matt', country: 'NZ' }]
Nested Queries
This feature allows you to perform queries on nested JSON structures. In this example, it filters the 'people' array to find entries where the 'address.city' is 'Auckland'.
const jsonQuery = require('json-query');
const data = { people: [{ name: 'Matt', address: { city: 'Auckland' } }, { name: 'Pete', address: { city: 'Sydney' } }] };
const result = jsonQuery('people[address.city=Auckland]', { data: data }).value;
console.log(result); // Output: [{ name: 'Matt', address: { city: 'Auckland' } }]
Aggregation
This feature allows you to aggregate data from JSON structures. In this example, it extracts the 'age' values from the 'people' array.
const jsonQuery = require('json-query');
const data = { people: [{ name: 'Matt', age: 30 }, { name: 'Pete', age: 40 }] };
const result = jsonQuery('people.age', { data: data }).value;
console.log(result); // Output: [30, 40]
Complex Conditions
This feature allows you to use complex conditions in your queries. In this example, it filters the 'people' array to find entries where the 'age' is greater than 30.
const jsonQuery = require('json-query');
const data = { people: [{ name: 'Matt', age: 30 }, { name: 'Pete', age: 40 }] };
const result = jsonQuery('people[age>30]', { data: data }).value;
console.log(result); // Output: [{ name: 'Pete', age: 40 }]
Other packages similar to json-query
lodash
Lodash is a modern JavaScript utility library delivering modularity, performance, and extras. It provides a wide range of utility functions for common programming tasks, including querying and manipulating JSON data. Compared to json-query, Lodash offers a broader set of functionalities but may require more verbose code for complex queries.
jmespath
JMESPath is a query language for JSON. It allows you to declaratively specify how to extract elements from a JSON document. JMESPath is more specialized for querying JSON data compared to json-query and offers a more expressive query language.
jsonpath
JSONPath is a query language for JSON, similar to XPath for XML. It allows you to navigate and query JSON data structures. JSONPath is similar to json-query in its purpose but uses a different syntax and may offer different features.
JSON Query
Retrieves values from JSON objects for data binding. Offers params, nested queries, deep queries, custom reduce/filter functions and simple boolean logic.
Used internally by JSON Context for data binding.
jsonQuery(query, options)
Specify a query and what to query - returns an object that describes the result of the query.
var context = {
people: [
{name: 'Matt', country: 'NZ'},
{name: 'Pete', country: 'AU'}
]
}
jsonQuery('people[country=NZ].name', {
rootContext: context
})
options:
- rootContext: The main JS object to query.
- context (optional): The current object we're interested in. Is accessed in query by starting with
.
- parent (optional): An additional context for looking further up the tree. Is accessed by
..
- filters: Specify an object containing filter functions. Accessed by ':filterName'
- force (optional): Specify an object to be returned from the query if the query fails - it will be saved into the place the query expected the object to be.
Queries
Queries are strings that describe an object or value to pluck out, or manipulate from the context object. The syntax is a little bit CSS, a little bit JS, but pretty powerful.
Accessing properties (dot notation)
person.name
Array accessors
people[0]
Array filter
people[country=NZ]
Or syntax
person.greetingName|person.name
Deep queries
Search through multiple levels of Objects/Arrays
var context = {
grouped_people: {
'friends': [
{name: 'Steve', country: 'NZ'},
{name: 'Bob', country: 'US'}
],
'enemies': [
{name: 'Evil Steve', country: 'AU'}
]
}
}
jsonQuery('grouped_people[][country=NZ]', {rootContext: context})
Inner queries
var context = {
page: {
id: 'page_1',
title: 'Test'
},
comments_lookup: {
'page_1': [
{id: 'comment_1', parent_id: 'page_1', content: "I am a comment"}
]
}
}
jsonQuery('comments_lookup[{page.id}]', {rootContext: context})
Filter functions
Allows to to hack the query system to do just about anything.
Some nicely contrived examples:
var filters = {
greetingName: function(input){
if (input.knownAs){
return input.known_as
} else {
return input.name
}
}
},
and: function(input, params){
return input && params.args[0]
},
text: function(input, params){
return params.args[0]
},
then: function(input, params){
if (input){
return params.args[0]
} else {
return params.args[1]
}
}
}
var context = {
is_fullscreen: true,
is_playing: false,
user: {
name: "Matthew McKegg",
known_as: "Matt"
}
}
jsonQuery('user:greetingName', {
rootContext: context, filters: filters
}).value
jsonQuery(['is_fullscreen:and({is_playing}):then(?, ?)', "Playing big!", "Not so much"], {
rootContext: context, filters: filters
}).value
jsonQuery(':text(This displays text cos we made it so)', {
filters: filters
}).value
Context
Specifying context ('rootContext', 'context', and 'parent' options) is good for databinding and working on a specific object and still keeping the big picture available.
var data = {
styles: {
bold: 'font-weight:strong',
red: 'color: red'
},
paragraphs: [
{content: "I am a red paragraph", style: 'red'},
{content: "I am a bold paragraph", style: 'bold'},
],
}
var pageHtml = ''
data.paragraphs.forEach(function(paragraph){
var style = jsonQuery('styles[{.style}]', {rootContext: data, context: paragraph}).value
var content = jsonQuery('.content', rootContext: data, context: paragraph)
pageHtml += "<p style='" + style "'>" + content + "</p>"
})
Query Params
Params can be specified by passing in an array with the first param the query (with ? params) and subsequent params.
jsonQuery(['people[country=?]', 'NZ'])
Dynamic Queries
Dynamic queries are asynchronous and can execute custom functions to get their data. It's a handy interface over the basic tokenizer.
jsonQuery.dynamic(query, options)
Too complicated for me to remember!