{"id":13526303,"url":"https://github.com/nemtsov/json-mask","last_synced_at":"2025-04-14T08:15:47.030Z","repository":{"id":37374647,"uuid":"11362272","full_name":"nemtsov/json-mask","owner":"nemtsov","description":"Tiny language and engine for selecting specific parts of a JS object, hiding the rest.","archived":false,"fork":false,"pushed_at":"2022-06-21T03:43:00.000Z","size":485,"stargazers_count":866,"open_issues_count":4,"forks_count":44,"subscribers_count":12,"default_branch":"main","last_synced_at":"2025-04-14T08:15:43.897Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nemtsov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-07-12T06:32:43.000Z","updated_at":"2025-03-14T06:25:51.000Z","dependencies_parsed_at":"2022-07-12T16:17:39.575Z","dependency_job_id":null,"html_url":"https://github.com/nemtsov/json-mask","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nemtsov%2Fjson-mask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nemtsov%2Fjson-mask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nemtsov%2Fjson-mask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nemtsov%2Fjson-mask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nemtsov","download_url":"https://codeload.github.com/nemtsov/json-mask/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248843955,"owners_count":21170495,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T06:01:27.758Z","updated_at":"2025-04-14T08:15:46.912Z","avatar_url":"https://github.com/nemtsov.png","language":"JavaScript","readme":"# JSON Mask [![Build Status](https://github.com/nemtsov/json-mask/actions/workflows/node.js.yml/badge.svg)](https://github.com/nemtsov/json-mask/actions/workflows/node.js.yml) [![NPM version](https://img.shields.io/npm/v/json-mask.svg)](https://www.npmjs.com/package/json-mask) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)\n\n\u003cimg src=\"https://raw.github.com/nemtsov/json-mask/master/logo.png\" align=\"right\" width=\"267px\" /\u003e\n\nThis is a tiny language and an engine for selecting specific parts of a JS object, hiding/masking the rest.\n\n```js\nvar mask = require('json-mask');\nmask({ p: { a: 1, b: 2 }, z: 1 }, 'p/a,z'); // {p: {a: 1}, z: 1}\n```\n\nThe main difference between JSONPath / JSONSelect and this engine is that JSON Mask\n**preserves the structure of the original input object**.\nInstead of returning an array of selected sub-elements (e.g. `[{a: 1}, {z: 1}]` from example above),\nit filters-out the parts of the object that you don't need,\nkeeping the structure unchanged: `{p: {a: 1}, z: 1}`.\n\nThis is important because JSON Mask was designed with HTTP resources in mind,\nthe structure of which I didn't want to change after the unwanted fields\nwere masked / filtered.\n\nIf you've used the Google APIs, and provided a `?fields=` query-string to get a\n[Partial Response](https://developers.google.com/gdata/docs/2.0/reference#PartialResponse), you've\nalready used this language. The desire to have partial responses in\nmy own Node.js-based HTTP services was the reason I wrote JSON Mask.\n\n_For [express](http://expressjs.com/) users, there's an\n[express-partial-response](https://github.com/nemtsov/express-partial-response) middleware.\nIt will integrate with your existing services with no additional code\nif you're using `res.json()` or `res.jsonp()`. And if you're already using [koa](https://github.com/koajs/koa.git)\ncheck out the [koa-json-mask](https://github.com/nemtsov/koa-json-mask) middleware._\n\nThis library has no dependencies. It works in Node as well as in the browser.\n\n**Note:** the 1.5KB (gz), or 4KB (uncompressed) browser build is in the `/build` folder.\n\n## Syntax\n\nThe syntax is loosely based on XPath:\n\n- `a,b,c` comma-separated list will select multiple fields\n- `a/b/c` path will select a field from its parent\n- `a(b,c)` sub-selection will select many fields from a parent\n- `a/*/c` the star `*` wildcard will select all items in a field\n\nTake a look at `test/index-test.js` for examples of all of these and more.\n\n## Grammar\n\n```\n     Props ::= Prop | Prop \",\" Props\n      Prop ::= Object | Array\n    Object ::= NAME | NAME \"/\" Prop\n     Array ::= NAME \"(\" Props \")\"\n      NAME ::= ? all visible characters except \"\\\" ? | EscapeSeq | Wildcard\n  Wildcard ::= \"*\"\n EscapeSeq ::= \"\\\" ? all visible characters ?\n```\n\n## Examples\n\nIdentify the fields you want to keep:\n\n```js\nvar fields = 'url,object(content,attachments/url)';\n```\n\nFrom this sample object:\n\n```js\nvar originalObj = {\n  id: 'z12gtjhq3qn2xxl2o224exwiqruvtda0i',\n  url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',\n  object: {\n    objectType: 'note',\n    content:\n      'A picture... of a space ship... launched from earth 40 years ago.',\n    attachments: [\n      {\n        objectType: 'image',\n        url: 'http://apod.nasa.gov/apod/ap110908.html',\n        image: { height: 284, width: 506 }\n      }\n    ]\n  },\n  provider: { title: 'Google+' }\n};\n```\n\nHere's what you'll get back:\n\n```js\nvar expectObj = {\n  url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',\n  object: {\n    content:\n      'A picture... of a space ship... launched from earth 40 years ago.',\n    attachments: [\n      {\n        url: 'http://apod.nasa.gov/apod/ap110908.html'\n      }\n    ]\n  }\n};\n```\n\nLet's test that:\n\n```js\nvar mask = require('json-mask');\nvar assert = require('assert');\n\nvar maskedObj = mask(originalObj, fields);\nassert.deepEqual(maskedObj, expectObj);\n```\n\n### Escaping\n\nIt is also possible to get keys that contain `,*()/` using `\\` (backslash) as escape character.\n\n```json\n{\n  \"metadata\": {\n    \"labels\": {\n      \"app.kubernetes.io/name\": \"mysql\",\n      \"location\": \"WH1\"\n    }\n  }\n}\n```\n\nYou can filter out the location property by `metadata(labels(app.kubernetes.io\\/name))` mask.\n\nNOTE: In [JavaScript String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) you must escape backslash with another backslash:\n```js\nvar fields = 'metadata(labels(app.kubernetes.io\\\\/name))'\n```\n\n### Partial Responses Server Example\n\nHere's an example of using `json-mask` to implement the\n[Google API Partial Response](https://developers.google.com/gdata/docs/2.0/reference#PartialResponse)\n\n```js\nvar http = require('http');\nvar url = require('url');\nvar mask = require('json-mask');\nvar server;\n\nserver = http.createServer(function(req, res) {\n  var fields = url.parse(req.url, true).query.fields;\n  var data = {\n    firstName: 'Mohandas',\n    lastName: 'Gandhi',\n    aliases: [\n      {\n        firstName: 'Mahatma',\n        lastName: 'Gandhi'\n      },\n      {\n        firstName: 'Bapu'\n      }\n    ]\n  };\n  res.writeHead(200, { 'Content-Type': 'application/json' });\n  res.end(JSON.stringify(mask(data, fields)));\n});\n\nserver.listen(4000);\n```\n\nLet's test it:\n\n```bash\n$ curl 'http://localhost:4000'\n{\"firstName\":\"Mohandas\",\"lastName\":\"Gandhi\",\"aliases\":[{\"firstName\":\"Mahatma\",\"lastName\":\"Gandhi\"},{\"firstName\":\"Bapu\"}]}\n\n$ # Let's just get the first name\n$ curl 'http://localhost:4000?fields=lastName'\n{\"lastName\":\"Gandhi\"}\n\n$ # Now, let's just get the first names directly as well as from aliases\n$ curl 'http://localhost:4000?fields=firstName,aliases(firstName)'\n{\"firstName\":\"Mohandas\",\"aliases\":[{\"firstName\":\"Mahatma\"},{\"firstName\":\"Bapu\"}]}\n```\n\n**Note:** a few more examples are in the `/example` folder.\n\n## Command Line Interface - CLI\n\nWhen installed globally using `npm i -g json-mask` you can use it like:\n\n`json-mask \"\u003cfields\u003e\" \u003cinput\u003e [\u003coutput\u003e]`\n\n### Examples\n\nStream from online resource:\n\n`curl https://api.myjson.com/bins/krrxw | json-mask \"url,object(content,attachments/url)\"`\n\nRead from file and write to output file:\n\n`json-mask \"url,object(content,attachments/url)\" input.json \u003e output.json`\n\nRead from file and print redirect to file:\n\n`json-mask \"url,object(content,attachments/url)\" input.json \u003e output.json`\n\n## CDN\n\n**unpkg**\n\n- `https://unpkg.com/json-mask/build/jsonMask.js`\n- `https://unpkg.com/json-mask/build/jsonMask.min.js`\n\n## License\n\n[MIT](/LICENSE)\n","funding_links":[],"categories":["Repository","JavaScript","Queries","Packages","Number"],"sub_categories":["Object / JSON / JSON Schema","Parsing"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnemtsov%2Fjson-mask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnemtsov%2Fjson-mask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnemtsov%2Fjson-mask/lists"}