Catalog npm
Back to packageRELEASE DETAILS

1.0.9

npm

1liner

Query JSON with one line of code.

1linerjmespathjs object queryjsonjson queryjsonpathltraversal
Published6 Nov 2020
Direct dependencies14
Transitive dependenciesNot calculated

README

Current package documentation

1Liner

version downloads

1Liner, or simply L is a super fast (10000 query executions take 150ms) and lightweight (< 35 kb minified) JavaScript library for the browser or for Node.js that allows querying of JSON with one tiny line of code.

Why?

Fetching data from a JSON can be cumbersome and always requires too much code. Wouldn't it be great to be able to fetch data, quickly, from a JSON with one simple line?

const L = require('1liner');
const obj = new L({
    propose: {
        address: {
            line_1: "39944 Morissette Trail",
            line_2: "Gulgowski Wells",
            postcode: "AB13RT",
            county: "Gloucestershire",
            country: "GB"
        },
        convictions: [{
            code: "SP50",
            points: 4,
        },
        {
            code: "SP50",
            points: 2,
        },
        {
            code: "SP30",
            points: 1,
        }]
    },
    additional_drivers: [{
        name: 'Ted',
        age: 24
    }, {
        name: 'Mary',
        age: 30
    }]
});

/*
* Normal object syntax
*/ 
obj.query('proposer.address.postcode'); // "AB13RT" 

/*
* Normal object then map on array element
*/ 
obj.query('proposer.convictions.map(code)'); // ["SP50", "SP50", "SP30"]

/*
* Normal object then chain array element filter on filter
*/ 
obj.query('proposer.convictions.filter(points<=2).filter(code=SP30).map(code)'); // ["SP30"]
obj.query('proposer.convictions.filter(points<=2).filter(code="SP30").map(code)'); // ["SP30"]

/*
* Array first element so filter applied immediately
*/ 
obj.query('additional_drivers.filter(age>24).map(name)'); // ["Mary"]

Installation

npm install --save 1liner

Usage

Node.js

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        claims: [{
            code: "A",
            at_fault: false,
        }]
    }    
});

obj.query('proposer.title'); // "MR"
obj.query('proposer.claims.map(code)'); // ["A"]
obj.query('proposer.age') - 10; // 23

Browsers

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/caljrimmer/1liner@latest/dist/index.js"></script>

A global variable window.L or simply L is created.

Operators

See test file for more details.

- count

Counts the number of items in an array. It can be used after a filter has been applied.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        claims: [{
            code: "A",
            at_fault: false,
        },
        {
            code: "W",
            at_fault: false,
        }]
    }    
});

obj.query('proposer.claims.count()'); // 2
obj.query('proposer.claims.filter(code=W).count()'); // 1
obj.query('proposer.claims.filter(code="W").count()'); // 1

- min, max, mean, range, sum

Finding the min integer, max integer and range between the two.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP30",
            points: 2
        }]
    }    
});

obj.query('proposer.convictions.map(points).min()'); // 2
obj.query('proposer.convictions.map(points).max()'); // 4
obj.query('proposer.convictions.map(points).range()'); // 2
obj.query('proposer.convictions.map(points).mean()'); // 3
obj.query('proposer.convictions.sum(points)'); // 6

/**
 * Defaulting result on min, max, mean
 */
 
obj.query('proposer.convictions.filter(points=0).min(10)'); // 10
obj.query('proposer.convictions.filter(points=0).max(1)'); // 1
obj.query('proposer.convictions.filter(points=0).mean(3)'); // 3

- map

Returns an array of the selected key within a collection of items.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP30",
            points: 2
        }]
    }    
});

obj.query('proposer.convictions.map(code)'); // ["SP50", "SP30"]

- filter

Returns a filtered collection based on a criteria.

Filters work on strings and numbers. Dates will need to be converted in to numbers (UNIX timestamps) to be filtered.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP30",
            points: 2
        }],
        claims: [{
            code: "A",
            at_fault: false,
        },
        {
            code: "W",
            at_fault: true,
        }]
    }    
});

obj.query('proposer.convictions.filter(code=SP30)'); // [{ code: "SP30", points: 2 }]
obj.query('proposer.convictions.filter(code="SP30")'); // [{ code: "SP30", points: 2 }]
obj.query('proposer.convictions.filter(code=SP30).map(points)'); // [2]
obj.query('proposer.convictions.filter(code!=SP30).map(points)'); // [4]
obj.query('proposer.convictions.filter(points<4).map(code)'); // ["SP30"]
obj.query('proposer.convictions.filter(points<=4).map(code)'); // ["SP50", "SP30"]
obj.query('proposer.convictions.filter(points>2).map(code)'); // ["SP50"]
obj.query('proposer.convictions.filter(points>=2).map(code)'); // ["SP50", "SP30"]
obj.query('proposer.claims.filter(at_fault=true).map(code)'); // ["W"]
obj.query('proposer.claims.filter(at_fault=false).count()'); // 1

- unique

Returns an array of the unique items.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP50",
            points: 2
        }]
    }    
});

obj.query('proposer.convictions.unique(code).count()'); // 1

- exists

Checks if property value exists i.e. not null, undefined, empty string or 0.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        middle_name: "",
        last_names: "Smith",
        age: 0,
        spouse: null
    }    
});

obj.query('proposer.middle_name.exists()'); // "false"
obj.query('proposer.age.exists()'); // "false"
obj.query('proposer.spouse.exists()'); // "false"
obj.query('proposer.title.exists()'); // "true"

- default

If property is undefined then it will return a defined default number or string

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        middle_name: "",
        last_names: "Smith",
        age: 0,
        spouse: null
    }    
});

obj.query('proposer.country.default(GB)'); // "GB"
obj.query('proposer.country.default("GB")'); // "GB"
obj.query('proposer.height.default(180)'); // 180
obj.query('proposer.first_names.default("bob")'); // "John"

- date, age

If property is a date, then you can use date() to find a hour, date, month or year from the date string, or use age() to find the age since now in hours, days, months or years.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        dob: "1990-01-01"
    }    
});

obj.query('proposer.dob.date(YY)'); // 1990
obj.query('proposer.dob.date(MM)'); // 1
obj.query('proposer.dob.date(DD)'); // 1
obj.query('proposer.dob.date(HH)'); // 0

//assuming the date now is 2022-01-01

obj.query('proposer.dob.age(YY)'); // 32
obj.query('proposer.dob.age(MM)'); // 384
obj.query('proposer.dob.age(DD)'); // 140160
obj.query('proposer.dob.age(HH)'); // 3363840

A second argument can be provided to point at a date in the object instead of using now. This must be a top-level key in the object.

const L = require('1liner');

const obj = new L({
    created_at: '2022-01-01',
    proposer: {
        title: "MR",
        first_names: "John",
        dob: "1990-01-01"
    }    
});

obj.query('proposer.dob.age(YY, created_at)'); // 32
obj.query('proposer.dob.age(MM, created_at)'); // 384
obj.query('proposer.dob.age(DD, created_at)'); // 140160
obj.query('proposer.dob.age(HH, created_at)'); // 3363840

Date and age work with arrays.

const L = require('1liner');

const obj = new L({
    created_at: '2022-01-01',
    proposer: {
        title: "MR",
        first_names: "John",
        dob: "1990-01-01",
        convictions: [{
            code: "SP50",
            points: 4,
            date: "2019-01-01",
        },
        {
            code: "SP30",
            points: 2,
            date: "2020-01-01",
        }]
    }    
});

obj.query('proposer.convictions.map(date).age(YY, created_at)'); // [ 3 , 2 ]
obj.query('proposer.convictions.map(date).age(MM, created_at)'); // [ 36 , 24 ]
obj.query('proposer.convictions.map(date).age(DD, created_at)'); // [ 1095 , 730 ]

- regex

If property is a string, then you can use regex() to parse a regular expression against the string and return the first match.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        home_postcode: "W64TR",
        shipping_postcode: "PO314RT"
    }    
});

obj.query('proposer.home_postcode.regex(^[A-Za-z]{2}|^[A-Za-z]{1})'); // W
obj.query('proposer.shipping_postcode.regex(^[A-Za-z]{2}|^[A-Za-z]{1})'); // PO

Multiple Queries

Returns an result from multiple queries. The queries need to return numbers as values otherwise an error with be thrown. The queries can be replaced with numbers too.

Multi-query options are min, max or range.

Example:

const L = require('1liner');

const obj = new L({
    proposer: {
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        height: 180,
        weight: 100,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP50",
            points: 2
        }]
    }    
});

obj.query('min([proposer.weight, proposer.height])'); // 100
obj.query('max([proposer.weight, proposer.height])'); // 180
obj.query('min([100, proposer.height])'); // 100
obj.query('max([100, proposer.height])'); // 180
obj.query('range([proposer.weight, proposer.height])'); // 80

each.

Returns an array of results based on the query responses to each of the children queries. This is useful if you wish to aggregate each child node instead of all together. Each (each.) can only be used as the first segment declaration (i.e. first part of the query string) and can not be wrapped by min, max or range as the result can be integers, strings or nested arrays.

Example:

const L = require('1liner');

const obj = new L({
    additional_drivers: [{
        title: "MR",
        first_names: "John",
        last_names: "Smith",
        age: 33,
        height: 180,
        weight: 100,
        convictions: [{
            code: "SP50",
            points: 4
        },
        {
            code: "SP50",
            points: 2
        }]
    },{
        title: "MRS",
        first_names: "Jane",
        last_names: "Smith",
        age: 30,
        height: 120,
        weight: 60,
        convictions: [{
            code: "SP10",
            points: 0
        }]
    }]    
});

obj.query('each.additional_drivers.map(convictions).count()'); // [2, 1]
obj.query('additional_drivers.map(convictions).count()'); // 3
obj.query('each.additional_drivers.map(convictions).map(code)'); // [['SP50', 'SP50'], ['SP10']]
obj.query('additional_drivers.map(convictions).map(code)'); // ['SP50', 'SP50', 'SP10']

Testing

Node.js

Install the dev dependencies:

$ npm install 1liner --development

Then navigate to the installed directory:

$ cd node_modules/1liner/

Run test package:

$ npm test

Speed

  • Small Object (2.5KB) - 10000 query executions takes 150ms
  • Large Object (2.5MB) - 1000 query executions takes 1094ms

Bundling

npm run bundle
npm publish

Contributions

If you contribute to this library, just modify index.js, index.spec.js, and update README.md. I'll update the website docs and generate the new dist/index.js, changelog and version.

Alternative packages

The following packages allow more sophisticated querying of JSON.

License

Licensed under GNU GENERAL PUBLIC LICENSE.

Copyright (C) 2020 Callum Rimmer callum@deadtrendy.co.uk

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Declared dependencies 14

Native requirements
14 direct targetsNot calculated transitive count
Package / targetRequirementRelationship
lodash.flatten
Environment
{
  "local_name": "lodash.flatten",
  "alias": false,
  "peer_metadata": null
}
^4.4.0runtime
lodash.get
Environment
{
  "local_name": "lodash.get",
  "alias": false,
  "peer_metadata": null
}
^4.4.2runtime
lodash.isarray
Environment
{
  "local_name": "lodash.isarray",
  "alias": false,
  "peer_metadata": null
}
^4.0.0runtime
lodash.isnumber
Environment
{
  "local_name": "lodash.isnumber",
  "alias": false,
  "peer_metadata": null
}
^3.0.3runtime
lodash.isundefined
Environment
{
  "local_name": "lodash.isundefined",
  "alias": false,
  "peer_metadata": null
}
^3.0.1runtime
lodash.max
Environment
{
  "local_name": "lodash.max",
  "alias": false,
  "peer_metadata": null
}
^4.0.1runtime
lodash.mean
Environment
{
  "local_name": "lodash.mean",
  "alias": false,
  "peer_metadata": null
}
^4.1.0runtime
lodash.meanby
Environment
{
  "local_name": "lodash.meanby",
  "alias": false,
  "peer_metadata": null
}
^4.10.0runtime
lodash.min
Environment
{
  "local_name": "lodash.min",
  "alias": false,
  "peer_metadata": null
}
^4.0.1runtime
lodash.round
Environment
{
  "local_name": "lodash.round",
  "alias": false,
  "peer_metadata": null
}
^4.0.4runtime
lodash.sumby
Environment
{
  "local_name": "lodash.sumby",
  "alias": false,
  "peer_metadata": null
}
^4.6.0runtime
lodash.uniqby
Environment
{
  "local_name": "lodash.uniqby",
  "alias": false,
  "peer_metadata": null
}
^4.7.0runtime
jest
Environment
{
  "local_name": "jest",
  "alias": false,
  "peer_metadata": null
}
^25.5.4development
parcel
Environment
{
  "local_name": "parcel",
  "alias": false,
  "peer_metadata": null
}
^1.12.4development

Distribution files

1 collected
Distribution 1

Source distribution

Source file
Checksums from source
{
  "integrity": "sha512-OORHLNF6jIf67l9PdMrE3r2ycUupxDeANLY9ATxvhMPzOlXKm8bMhphpi3z0NCNKO6d8/V/x/0rRN7uO3RyD1g==",
  "shasum": "e2a972329bac00192be44d930c7fe632219fc085",
  "tarball": "https://registry.npmjs.org/1liner/-/1liner-1.0.9.tgz",
  "fileCount": 9,
  "unpackedSize": 518070,
  "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfpWH5CRA9TVsSAnZWagAApJAP/2RL0ouwFDV4RDDLgQjU\nBvzWmh/n7c6N/nkog2OV0r4DngGiFcFxJ7pOJMQwGrI0QhtvBHwC0Dwkdycx\nXx1myWzSemzO6L9ZQ6QTgdYcgqpIFogEv9hwAlvuCglnGpgvKAEvfjMTNvS8\n5KwDF9rjG3r+M9jbhQntAfV7GkqfkzZaXDMyK4scHi/5DJFNCQGIolfZEmV4\nhbnLCWtORZ1I775LtB1rxPIGKIM1PkYt9x2nJ0Lc1OPyLfkz1WA+yXU/1ZAM\nnx6hQmC4AjkwrD7nxUsiy2ol5fxMbmsmiGe5+Ey1dxIeS0y76zUPJw6S+aK0\nwGE7Cpd6b0oRMZy7V6xnehEy4knuxsVbaDMpoH+MtBfUhwfyD2SGzBuHEmWb\njGCJZ7Sf7qDXMnjvTt5QwB0z1yVYkAUypPbw+xUNF3RGLk9vTbz1RCSINeIt\nWkCn1CX7SW7K+UGe1VZ1kooLXhSJf815HyaxIwMwQ+XAjFrpdKvfJSmcWoMl\nhKOSqUMAaJR7GuYnstSKQTmxjNmSONXNH3AtW3mv5QDHYLdlp9R1jKhisuQ7\n0Awq5ef7ksn6WfmBgRhkrfA4NZZtdjRLYvOQU/jIu9arlw157pn1fFdlHCEe\nWU8aiu4E14836OYQLujyn9q5LKCzLxjILQKFBcwMCZjv0xs2gPaMQ8DGZUs4\nXzin\r\n=72Xq\r\n-----END PGP SIGNATURE-----\r\n",
  "signatures": [
    {
      "keyid": "SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA",
      "sig": "MEUCIAqBkQamjM3dnFHrk/a9jtXY86iY6IufeJZCnFxGRzsjAiEAxY6wD6kc4NAy9mpVldJfnI6/S+fTcs8R8dRFWk8ILgs="
    }
  ]
}

Repository

PENDING
caljrimmer/1liner

Shared repository data · GitHub

License detected in repository
Not collected

Metadata history

Meaningful changes
Current collected state Current

Observed since 20 Oct, 18:31 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package_version:7f2df6087b15ce30bd80cae5e6b22aaac0e439bed72e63a90e6258e6dfd2b5b1

Other collected versions

1.0.1731 Oct1.0.1631 Oct1.0.1520 Apr1.0.1417 Mar1.0.1327 Feb1.0.1222 FebView all collected versions →