← 全部工具

json-mask

热度 65 更新于 开发与构建

Tiny language and engine for selecting specific parts of a JS object, hiding the rest.

npmauto-collected

安装

npm
npm install -g json-mask

通过 npm 安装。

JSON Mask [](https://github.com/nemtsov/json-mask/actions/workflows/node.js.yml) [](https://www.npmjs.com/package/json-mask) [](http://standardjs.com/)

<img src="https://raw.github.com/nemtsov/json-mask/master/logo.png" align="right" width="267px" /

This is a tiny language and an engine for selecting specific parts of a JS object, hiding/masking the rest.

var mask = require('json-mask');
mask({ p: { a: 1, b: 2 }, z: 1 }, 'p/a,z'); // {p: {a: 1}, z: 1}

The main difference between JSONPath / JSONSelect and this engine is that JSON Mask preserves the structure of the original input object. Instead of returning an array of selected sub-elements (e.g. [{a: 1}, {z: 1}] from example above), it filters-out the parts of the object that you don't need, keeping the structure unchanged: {p: {a: 1}, z: 1}.

This is important because JSON Mask was designed with HTTP resources in mind, the structure of which I didn't want to change after the unwanted fields were masked / filtered.

If you've used the Google APIs, and provided a ?fields= query-string to get a Partial Response, you've already used this language. The desire to have partial responses in my own Node.js-based HTTP services was the reason I wrote JSON Mask.

For express users, there's an express-partial-response middleware. It will integrate with your existing services with no additional code if you're using res.json() or res.jsonp(). And if you're already using koa check out the koa-json-mask middleware.

This library has no dependencies. It works in Node as well as in the browser.

Note: the 1.5KB (gz), or 4KB (uncompressed) browser build is in the /build folder.

Syntax

The syntax is loosely based on XPath:

  • a,b,c comma-separated list will select multiple fields
  • a/b/c path will select a field from its parent
  • a(b,c) sub-selection will select many fields from a parent
  • a//c the star wildcard will select all items in a field

Take a look at test/index-test.js for examples of all of these and more.

Grammar

     Props ::= Prop | Prop "," Props
      Prop ::= Object | Array
    Object ::= NAME | NAME "/" Prop
     Array ::= NAME "(" Props ")"
      NAME ::= ? all visible characters except "\" ? | EscapeSeq | Wildcard
  Wildcard ::= "*"
 EscapeSeq ::= "\" ? all visible characters ?

Examples

Identify the fields you want to keep: