How to use jsonpath - 10 common examples

To help you get started, we’ve selected a few jsonpath 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 RiseVision / rise-node / src / app.ts View on Github external
.option('-o, --override-config ', 'Override single config item', (opt, opts) => {
    if (typeof(opts) === 'undefined') {
      opts = [];
    }
    const [path, val] = opt.split('=');
    if (typeof(path) === 'undefined' || typeof(val) === 'undefined') {
      // tslint:disable-next-line
      console.warn('Invalid format for invalid config. Correct is -> jsonpath=value');
      return opts;
    }
    try {
      jp.parse(path);
    } catch (e) {
      // tslint:disable-next-line
      console.warn('JSONPath is invalid', e);
    }
    opts.push({ path, val });
    return opts;
  })
  .parse(process.argv);
github RiseVision / rise-node / packages / core-launchpad / src / app.ts View on Github external
(opt, opts) => {
      if (typeof opts === 'undefined') {
        opts = [];
      }
      const [path, val] = opt.split('=');
      if (typeof path === 'undefined' || typeof val === 'undefined') {
        // tslint:disable-next-line
        console.warn(
          'Invalid format for invalid config. Correct is -> jsonpath=value'
        );
        return opts;
      }
      try {
        jp.parse(path);
      } catch (e) {
        // tslint:disable-next-line
        console.warn('JSONPath is invalid', e);
      }
      opts.push({ path, val });
      return opts;
    }
  );
github Redocly / swagger-repo / lib / index.js View on Github external
function inlineHeaders(spec) {
  jpath.apply(spec, '$..[?(@.$ref)]', function(value) {
    if (!value.$ref.startsWith('#/headers')) {
      return value;
    }

    // TODO: throw if (!_.omit(value, '$ref').isEmpty())
    return jsonpointer.get(spec, value.$ref.substring(1));
  });
  delete spec.headers;
}
github Azure / oav / lib / autorestPlugin / extension.ts View on Github external
try {
    specVal.validateOperations()
    const specValidationResult = specVal.specValidationResult
    for (const [op, operation] of entries(specValidationResult.operations)) {
      const xmsExamplesNode = operation["x-ms-examples"]
      if (xmsExamplesNode === undefined) {
        throw new Error("xmsExamplesNode is undefined")
      }
      const scenarios = xmsExamplesNode.scenarios
      for (const [scenario, scenarioItem] of entries(scenarios)) {
        // invalid? meaning that there's an issue found in the validation
        if (scenarioItem.isValid === false) {
          // get path to x-ms-examples in swagger
          const xmsexPath = linq
            .from(
              jsonPath.nodes(swagger, `$.paths[*][?(@.operationId==='${op}')]["x-ms-examples"]`)
            )
            .select(x => x.path)
            .firstOrDefault()
          if (!xmsexPath) {
            throw new Error("Model Validator: Path to x-ms-examples not found.")
          }
          // console.error(JSON.stringify(scenarioItem, null, 2));
          let result = new FormattedOutput(
            "verbose",
            { scenarioItem, scenario },
            [modelValidationCategory],
            "Model validator found issue (see details).",
            [{ document: swaggerFileName, Position: { path: xmsexPath } }]
          )
          formattedResult.push(result)
github TryGhost / Ghost / core / server / lib / common / i18n.js View on Github external
if (coreStrings === undefined) {
            I18n.init();
        }

        if (options.isThemeString) {
            // If not in memory, load translations for theme
            if (themeStrings === undefined) {
                I18n.loadThemeTranslations();
            }
            // Both jsonpath's dot-notation and bracket-notation start with '$'
            // E.g.: $.store.book.title or $['store']['book']['title']
            // The {{t}} translation helper passes the default English text
            // The full Unicode jsonpath with '$' is built here
            // jp.stringify and jp.value are jsonpath methods
            // Info: https://www.npmjs.com/package/jsonpath
            path = jp.stringify(['$', msgPath]);
            candidateString = jp.value(themeStrings, path) || msgPath;
        } else {
            // Backend messages use dot-notation, and the '$.' prefix is added here
            // While bracket-notation allows any Unicode characters in keys for themes,
            // dot-notation allows only word characters in keys for backend messages
            // (that is \w or [A-Za-z0-9_] in RegExp)
            path = `$.${msgPath}`;
            candidateString = jp.value(coreStrings, path);
        }

        matchingString = candidateString || {};

        if (isObject(matchingString) || isEqual(matchingString, {})) {
            if (options.log) {
                logging.error(new errors.IncorrectUsageError({
                    message: `i18n error: path "${msgPath}" was not found`
github sdawood / dynamo-update-expression / src / dynamo-update-expression.spec.js View on Github external
const applyDeletes = (document, deletes, nullify = true) => {
        const modified = _.cloneDeep(document);
        // const modified = JSON.parse(JSON.stringify(document));
        for (const path of deletes) {
            const parent = jp.parent(modified, path);
            if (_.isArray(parent)) {
                const _subscript = /\[([\d]+)\]$/;
                const subscript = _subscript.exec(path)[1];
                if (nullify) {
                    parent[subscript] = null; // delete array['0'] doesn't work with jsonpath! list items should be deleted by setting to null or undefined,
                } else {
                    parent.splice(subscript, 1);
                }
            } else {
                delete parent[path.split('.').pop()];
            }
        }
        return modified;
    };
github Sundly / sundly / src / lib / parse_cda.js View on Github external
function getTimeline(result) {
  const entries = jp.query(result, '$.ClinicalDocument.entry')[0]
  const vitalSigns = jp.query(entries, '$[?(@.organizer.code.__code=="46680005")]')
  const observations = jp.query(vitalSigns, '$..observation')
  const keys = {
    'Height': 'height',
    'Body weight Measured': 'weight',
    'Heart rate': 'heart_rate',
    'Body Temperature': 'temperature'
  }
  const obTimeline = observations.map((observation) => {
    const effectiveTime = jp.query(observation, '$.effectiveTime.low.__value')[0]
    const datetime = moment(effectiveTime, 'YYYYMMDDTHHmmss-Z').format()
    const name = jp.query(observation, '$.code.__displayName')[0]
    const value = jp.query(observation, '$.value.__value')[0]
    // ToDo: Convert value scale based on units
    // const unit = jp.query(observation, '$.value.__unit')[0]

    return { datetime, [keys[name]]: value}
  })
github misenhower / splatoon2.ink / src / app / updater / updaters / FestivalsUpdater.js View on Github external
async processData(regionData) {
        // Fix alpha/bravo images for the Chicken vs. Egg Splatfest.
        // For some reason these got swapped out with images that have an opaque background
        // even though they started out with transparent images.
        jsonpath.apply(regionData, '$..images.alpha', value => value.replace(
            "/images/festival/a070cc6b405b4fb335992d824097acd8.png",
            "/images/festival/06b3b0b7773d9e6c4ac0a5cc5371fc32.png"
        ));
        jsonpath.apply(regionData, '$..images.bravo', value => value.replace(
            "/images/festival/00e4c5fdccd3720d07127084fc1f4152.png",
            "/images/festival/d93df77468714c6211e9377f39a559f4.png"
        ));

        // Download result ranking data
        let festivalIds = jsonpath.query(regionData, '$.results..festival_id');
        for (let id of festivalIds) {
            let filename = `${this.getOutputPath()}/festivals/${this.region.toLowerCase()}-${id}-rankings.json`;

            // Have we already downloaded these rankings?
            if (!fs.existsSync(filename)) {
                let splatnet = new SplatNet(this.region);
                this.info(`Retrieving rankings for festival ID ${id}`);
                try {
                    let rankings  = await this.handleRequest(splatnet.getFestivalRankings(id));
                    writeJson(filename, rankings);
github Azure / azure-openapi-validator / src / typescript / azure-openapi-validator / index.ts View on Github external
export async function run(
  document: string,
  openapiDefinition: any,
  sendMessage: (m: Message) => void,
  openapiType: OpenApiTypes,
  mergeState: MergeStates
) {
  const rulesToRun = rules.filter(rule => rule.mergeState === mergeState && rule.openapiType & openapiType)
  for (const rule of rulesToRun) {
    for (const section of nodes(openapiDefinition, rule.appliesTo_JsonQuery || "$")) {
      if (rule.run) {
        for (const message of rule.run(openapiDefinition, section.value, section.path.slice(1))) {
          handle(rule, message)
        }
      } else {
        for await (const message of rule.asyncRun(openapiDefinition, section.value, section.path.slice(1))) {
          handle(rule, message)
        }
      }
    }
  }

  function handle(rule: Rule, message: ValidationMessage) {
    const readableCategory = rule.category

    // try to extract provider namespace and resource type
github Azure / autorest / src / autorest-core / lib / ref / jsonpath.ts View on Github external
export function nodes(obj: T, jsonQuery: string): { path: JsonPath, value: any }[] {
  // jsonpath only accepts objects
  if (obj instanceof Object) {
    let result = jsonpath.nodes(obj, jsonQuery).map(x => { return { path: x.path.slice(1), value: x.value }; });
    const comp = (a: string, b: string) => a < b ? -1 : (a > b ? 1 : 0);
    result = result.sort((a, b) => comp(JSON.stringify(a.path), JSON.stringify(b.path)));
    result = result.filter((x, i) => i === 0 || JSON.stringify(x.path) !== JSON.stringify(result[i - 1].path));
    return result;
  } else {
    return matches(jsonQuery, []) ? [{ path: [], value: obj }] : [];
  }
}

jsonpath

Query JavaScript objects with JSONPath expressions. Robust / safe JSONPath engine for Node.js.

MIT
Latest version published 4 years ago

Package Health Score

67 / 100
Full package analysis