How to use jsonpath-plus - 10 common examples

To help you get started, we’ve selected a few jsonpath-plus examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github IBM / openapi-to-graphql / packages / openapi-to-graphql / lib / resolver_builder.js View on Github external
return resolveData.usedRequestOptions.url;
    }
    else if (value === '$method') {
        return resolveData.usedRequestOptions.method;
    }
    else if (value === '$statusCode') {
        return resolveData.usedStatusCode;
    }
    else if (value.startsWith('$request.')) {
        // CASE: parameter is previous body
        if (value === '$request.body') {
            return resolveData.usedPayload;
            // CASE: parameter in previous body
        }
        else if (value.startsWith('$request.body#')) {
            const tokens = JSONPath.JSONPath({
                path: value.split('body#/')[1],
                json: resolveData.usedPayload
            });
            if (Array.isArray(tokens) && tokens.length > 0) {
                return tokens[0];
            }
            else {
                httpLog(`Warning: could not extract parameter '${paramName}' from link`);
            }
            // CASE: parameter in previous query parameter
        }
        else if (value.startsWith('$request.query')) {
            return resolveData.usedParams[Oas3Tools.sanitize(value.split('query.')[1])];
            // CASE: parameter in previous path parameter
        }
        else if (value.startsWith('$request.path')) {
github kubernetes-client / javascript / src / cloud_auth.ts View on Github external
try {
            output = proc.execSync(cmd);
        } catch (err) {
            throw new Error('Failed to refresh token: ' + err.message);
        }

        const resultObj = JSON.parse(output);

        const tokenPathKeyInConfig = config['token-key'];
        const expiryPathKeyInConfig = config['expiry-key'];

        // Format in file is {}, so slice it out and add '$'
        const tokenPathKey = '$' + tokenPathKeyInConfig.slice(1, -1);
        const expiryPathKey = '$' + expiryPathKeyInConfig.slice(1, -1);

        config['access-token'] = jsonpath.JSONPath(tokenPathKey, resultObj);
        config.expiry = jsonpath.JSONPath(expiryPathKey, resultObj);
    }
}
github facebook / facebook-business-sdk-codegen / src / processors / SpecOverridingProcessor.js View on Github external
process(specs, metadata) {
    const language: string = metadata.language || '';
    const flags = metadata.mergedOverriding.flags;
    let APISpecs = specs.api_specs;
    const languageDef = codeGenLanguages[language];
    const specOverriding = metadata.mergedOverriding.spec_overriding;
    for (const clsName in specOverriding) {
      for (const jsonPath in specOverriding[clsName]) {
        const value = specOverriding[clsName][jsonPath];
        const $ = APISpecs[clsName] || {};
        const evalPathes =
          jsonPath === '$'
            ? ['$']
            : JSONPath.eval($, jsonPath, {resultType: 'path'});
        if (evalPathes.length === 0) {
          throw new Error(
            'MUST_FIX: cannot find JSON path need to be patched.\n' +
              clsName +
              '::' +
              jsonPath,
          );
        }

        if (value === null) {
          // Delete
          evalPathes.forEach((path: string) => {
            // Find the parent path before it
            // Since all paths are of the form $[..][..][..] we only need
            // to remove the last [..]
            const lastBracketPos = path.lastIndexOf('[');
github IBM / openapi-to-graphql / packages / openapi-to-graphql / src / resolver_builder.ts View on Github external
function extractToken(data: PreprocessingData, ctx: object) {
  const tokenJSONpath = data.options.tokenJSONpath
  const tokens = JSONPath.JSONPath({ path: tokenJSONpath, json: ctx })
  if (Array.isArray(tokens) && tokens.length > 0) {
    const token = tokens[0]
    return {
      access_token: token
    }
  } else {
    httpLog(
      `Warning: could not extract OAuth token from context at '${tokenJSONpath}'`
    )
    return {}
  }
}
github harver-engineering / bat / src / steps-fn.js View on Github external
async function responseBodyJsonPathMatches(path, value) {
    const { body } = await this.getResponse();
    const actualValue = JSONPath({ json: body, path })[0];
    expect(actualValue).to.match(new RegExp(value));
}
github harver-engineering / bat / src / steps-fn.js View on Github external
async function responseBodyJsonPathEquals(path, value) {
    const { body } = await this.getResponse();
    const actualValue = JSONPath({ json: body, path })[0];
    expect(actualValue).to.equalLoosely(this.replaceVars(value));
}
github json-schema-faker / json-schema-faker / dist / index.js View on Github external
return obj.map(function (x) { return resolve(x, data, values, property); });
  }

  if (obj.jsonPath) {
    var params = typeof obj.jsonPath !== 'object' ? {
      path: obj.jsonPath
    } : obj.jsonPath;
    params.group = obj.group || params.group || property;
    params.cycle = obj.cycle || params.cycle || false;
    params.reverse = obj.reverse || params.reverse || false;
    params.count = obj.count || params.count || 1;
    var key = (params.group) + "__" + (params.path);

    if (!values[key]) {
      if (params.count > 1) {
        values[key] = jsonpathPlus.JSONPath(params.path, data).slice(0, params.count);
      } else {
        values[key] = jsonpathPlus.JSONPath(params.path, data);
      }
    }

    if (params.cycle || params.reverse) {
      return cycle(values[key], params.reverse);
    }

    return pick$1(values[key]);
  }

  Object.keys(obj).forEach(function (k) {
    obj[k] = resolve(obj[k], data, values, k);
  });
  return obj;
github json-schema-faker / json-schema-faker / src / core / run.js View on Github external
if (obj.jsonPath) {
    const params = typeof obj.jsonPath !== 'object'
      ? { path: obj.jsonPath }
      : obj.jsonPath;

    params.group = obj.group || params.group || property;
    params.cycle = obj.cycle || params.cycle || false;
    params.reverse = obj.reverse || params.reverse || false;
    params.count = obj.count || params.count || 1;

    const key = `${params.group}__${params.path}`;

    if (!values[key]) {
      if (params.count > 1) {
        values[key] = JSONPath(params.path, data).slice(0, params.count);
      } else {
        values[key] = JSONPath(params.path, data);
      }
    }

    if (params.cycle || params.reverse) {
      return cycle(values[key], params.reverse);
    }

    return pick(values[key]);
  }

  Object.keys(obj).forEach(k => {
    obj[k] = resolve(obj[k], data, values, k);
  });
github magma / magma / symphony / app / fbcnms-projects / workflows-proxy / src / proxy / utils.js View on Github external
export function findValuesByJsonPath(
  json: mixed,
  path: string,
  resultType: string = 'all',
) {
  const result = JSONPath({json, path, resultType});
  logger.debug(`For path '${path}' found ${result.length} items`);
  return result;
}
github stoplightio / spectral / src / runner.ts View on Github external
callback: (result: any) => {
          lint(
            {
              path: JSONPath.toPathArray(result.path),
              value: result.value,
            },
            resolved,
            rule,
            functions,
            results,
          );
        },
      });

jsonpath-plus

A JS implementation of JSONPath with some additional operators

MIT
Latest version published 5 days ago

Package Health Score

85 / 100
Full package analysis