Security News
The Risks of Misguided Research in Supply Chain Security
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
json-query
Advanced tools
Retrieves values from JSON objects for data binding. Offers params, nested queries, deep queries, custom reduce/filter functions and simple boolean logic. Browserify compatible.
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.
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 }]
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 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 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.
Retrieves values from JSON objects for data binding. Offers params, nested queries, deep queries, custom reduce/filter functions and simple boolean logic.
$ npm install json-query
var jsonQuery = require('json-query')
jsonQuery(query, options)
Specify a query and what to query. Returns an object that describes the result of the query.
var data = {
people: [
{name: 'Matt', country: 'NZ'},
{name: 'Pete', country: 'AU'},
{name: 'Mikey', country: 'NZ'}
]
}
jsonQuery('people[country=NZ].name', {
data: data
}) //=> {value: 'Matt', parents: [...], key: 0} ... etc
data
or rootContext
: The main object to query.source
or context
(optional): The current object we're interested in. Accessed in query with .
.parent
(optional): An additional context for looking further up the tree. Accessed by ..
.locals
: Specify an object containing helper functions. Accessed by ':filterName'
. Expects function(input, args...)
with this
set to original passed in options.globals
: Falls back to globals when no local function found.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.allowRegexp
(optional): Enable the ~
operator. Before enabling regexp match to anyone, consider the user defined regular expression security concerns.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.
person.name
people[0]
people.name
=> return all the names of people
lookup[*]
By default only the first matching item will be returned:
people[name=Matt]
But if you add an asterisk (*
), all matching items will be returned:
people[*country=NZ]
You can use comparative operators:
people[*rating>=3]
Or use boolean logic:
people[* rating >= 3 & starred = true]
If options.enableRegexp
is enabled, you can use the ~
operator to match RegExp
:
people[*name~/^R/i]
You can also negate any of the above examples by adding a !
before the =
or ~
:
people[*country!=NZ]
person.greetingName|person.name
Search through multiple levels of Objects/Arrays using [**]
:
var data = {
grouped_people: {
'friends': [
{name: 'Steve', country: 'NZ'},
{name: 'Jane', country: 'US'},
{name: 'Mike', country: 'AU'},
{name: 'Mary', country: 'NZ'},
],
'enemies': [
{name: 'Evil Steve', country: 'AU'}
{name: 'Betty', country: 'NZ'},
]
}
}
var result = jsonQuery('grouped_people[**][*country=NZ]', {data: data}).value
The result
will be:
[
{name: 'Steve', country: 'NZ'},
{name: 'Mary', country: 'NZ'},
{name: 'Betty', country: 'NZ'}
]
var data = {
page: {
id: 'page_1',
title: 'Test'
},
comments_lookup: {
'page_1': [
{id: 'comment_1', parent_id: 'page_1', content: "I am a comment"}
]
}
}
// get the comments that match page's id
jsonQuery('comments_lookup[{page.id}]', {data: data})
Allows you to hack the query system to do just about anything.
Some nicely contrived examples:
var helpers = {
greetingName: function(input){
if (input.known_as){
return input.known_as
} else {
return input.name
}
},
and: function(inputA, inputB){
return inputA && inputB
},
text: function(input, text){
return text
},
then: function(input, thenValue, elseValue){
if (input){
return thenValue
} else {
return elseValue
}
}
}
var data = {
is_fullscreen: true,
is_playing: false,
user: {
name: "Matthew McKegg",
known_as: "Matt"
}
}
jsonQuery('user:greetingName', {
data: data, locals: helpers
}).value //=> "Matt"
jsonQuery(['is_fullscreen:and({is_playing}):then(?, ?)', "Playing big!", "Not so much"], {
data: data, locals: helpers
}).value //=> "Not so much"
jsonQuery(':text(This displays text cos we made it so)', {
locals: helpers
}).value //=> "This displays text cos we made it so"
Or you could add a select
helper:
jsonQuery('people:select(name, country)', {
data: data,
locals: {
select: function (input) {
if (Array.isArray(input)) {
var keys = [].slice.call(arguments, 1)
return input.map(function (item) {
return Object.keys(item).reduce(function (result, key) {
if (~keys.indexOf(key)) {
result[key] = item[key]
}
return result
}, {})
})
}
}
}
})
You can also use helper functions inside array filtering:
jsonQuery('people[*:recentlyUpdated]', {
data: data,
locals: {
recentlyUpdated: function (item) {
return item.updatedAt < Date.now() - (30 * 24 * 60 * 60 * 1000)
}
}
})
Specifying context (data
, source
, 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}]', {data: data, source: paragraph}).value
var content = jsonQuery('.content', data: data, source: paragraph) // pretty pointless :)
pageHtml += "<p style='" + style "'>" + content + "</p>"
})
Params can be specified by passing in an array with the first param the query (with ?
params) and subsequent params.
jsonQuery(['people[country=?]', 'NZ'])
MIT
FAQs
Retrieves values from JSON objects for data binding. Offers params, nested queries, deep queries, custom reduce/filter functions and simple boolean logic. Browserify compatible.
We found that json-query demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
Research
Security News
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.