Skip to content

rochejul/json-walker

npm version license Code Climate Known Vulnerabilities Node.js Unit Test

json-walker

Create a JSON walker api (nodejs/web) to walk through EcmaScript objects.

Motivation

We frequently need to go deeply in objects and to have some information, such as the path, etc...

Usage

We have two usages: Walker and IterableWalker. The first allows to define your own way to iterate. The second could be used as an iterable.

Walker usage

function grabProperties(value) {
  const properties = [];
  const walker = new Walker(value);
  let optionalWalkerMetadata;

  do {
    optionalWalkerMetadata = walker.nextStep();

    if (optionalWalkerMetadata.isSome()) {
      properties.push({
        path: optionalWalkerMetadata.value.propertyPath.toString(),
        type: optionalWalkerMetadata.value.propertyType,
        value: optionalWalkerMetadata.value.propertyValue,
      });
    }
  } while (optionalWalkerMetadata.isSome());

  return properties;
}

const secondLevel = { label: 'foo' };
const array = [secondLevel];
const firstLevel = { records: array };
const actual = grabProperties(firstLevel);

/* actual content:
 * [
    {
      path: 'records',
      type: 'array',
      value: [{ label: 'foo' }],
    },
    {
      path: 'records[0]',
      type: 'object',
      value: { label: 'foo' },
    },
    {
      path: 'records[0].label',
      type: 'string',
      value: 'foo',
    },
  ]
 */

IterableWalker usage

function grabProperties(value) {
  const properties = [];
  const walker = new IterableWalker(value);

  for (const value of walker) {
    properties.push({
      path: value.propertyPath.toString(),
      type: value.propertyType,
      value: value.propertyValue,
    });
  }

  return properties;
}

const secondLevel = { label: 'foo' };
const array = [secondLevel];
const firstLevel = { records: array };
const actual = grabProperties(firstLevel);

/* actual content:
 * [
    {
      path: 'records',
      type: 'array',
      value: [{ label: 'foo' }],
    },
    {
      path: 'records[0]',
      type: 'object',
      value: { label: 'foo' },
    },
    {
      path: 'records[0].label',
      type: 'string',
      value: 'foo',
    },
  ]
 */

Commands

  • npm run dev:build: Build the project over packages
  • npm run dev:check: Run tests and styling over packages
  • npm run dev:format: Format files over packages
  • npm run dev:format:check: Check files format over packages
  • npm run dev:linting: Lint files over packages
  • npm run dev:styling: Format and lint files over packages
  • npm run dev:publish: Publish all the packages on npm registry
  • npm test: Run tests over packages
  • npm run test:coverage: Run tests over packages and see coverage reports

Contributing

About

JSON walker api to go through EcmaScript objects

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published