How to use the jsonpath.nodes function in jsonpath

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 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 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 }] : [];
  }
}
github Redocly / swagger-repo / lib / index.js View on Github external
_.each(plugins, function(plugin) {
    plugin.init && plugin.init(spec, options);
    _.each(jpath.nodes(spec, plugin.pathExpression), function(node) {
      const name = _.last(node.path);
      const parent = jpath.value(spec, jpath.stringify(_.dropRight(node.path)));
      plugin.process(parent, name, node.path, spec);
    });
    plugin.finish && plugin.finish(spec);
  });
}
github Azure / azure-openapi-validator / src / typescript / azure-openapi-validator / rules / utilities / resourceUtils.ts View on Github external
private getSpecificOperationModels(httpVerb, code) {
    const models: Map = new Map()
    const getModel = node => {
      if (node && node.value) {
        const response = node.value
        if (response.schema && response.schema.$ref) {
          const modelName = this.stripDefinitionPath(response.schema.$ref)
          if (modelName) {
            this.addToMap(models, modelName, node.path[2] as string)
          }
        }
      }
    }
    for (const node of nodes(this.innerDoc, `$.paths.*.${httpVerb}.responses.${code}`)) {
      getModel(node)
    }
    for (const node of nodes(this.innerDoc, `$['x-ms-paths'].*.${httpVerb}.responses.${code}`)) {
      getModel(node)
    }
    return models
  }
github Azure / azure-openapi-validator / src / typescript / azure-openapi-validator / rules / UniqueXmsEnumName.ts View on Github external
*run(doc, node, path) {
    const msg: string = `Must not have duplicate name of x-ms-enum extension , make sure every x-ms-enum name unique.`
    if (node) {
      const enumMap = new Map()
      for (const section of nodes(node, "$..*[?(@.enum)]")) {
        if (section.value["x-ms-enum"] && isValidEnum(node.value)) {
          const enumName = section.value["x-ms-enum"].name.toLowerCase()
          if (enumMap.has(enumName)) {
            const curEnum = transformEnum(section.value.type, section.value.enum)
            const existingEnum = enumMap.get(enumName)
            /**
             * if existing , check if the two enums' enties is same.
             */
            if (
              existingEnum.length !== curEnum.length ||
              existingEnum.some((value, index) => curEnum[index].toLowerCase() !== value.toLowerCase())
            ) {
              yield { message: `${msg} The duplicate x-ms-enum name is ${enumName}`, location: path.concat(section.path.slice(1)) }
            }
          } else {
            enumMap.set(enumName, section.value.enum)
github magda-io / magda / magda-csw-connector / src / cswFuncs.ts View on Github external
function getResponsibleParties(dataset: any) {
    return jsonpath
        .nodes(dataset.json, "$..CI_ResponsibleParty[*]")
        .concat(jsonpath.nodes(dataset.json, "$..CI_Responsibility[*]"))
        .concat(
            jsonpath.nodes(
                dataset.json,
                "$..CI_Responsibility[?(@.party.CI_Organisation)]"
            )
        )
        .filter(obj => !obj.path.includes("thesaurusName"))
        .map(obj => obj.value);
}
github Azure / azure-openapi-validator / src / typescript / azure-openapi-validator / rules / utilities / resourceUtils.ts View on Github external
private *jsonPathIt(doc, jsonPath: string): Iterable {
    if (doc) {
      for (const node of nodes(doc, jsonPath)) {
        yield node.value
      }
    }
  }
github magda-io / magda / magda-csw-connector / src / cswFuncs.ts View on Github external
function getResponsibleParties(dataset: any) {
    return jsonpath
        .nodes(dataset.json, "$..CI_ResponsibleParty[*]")
        .concat(jsonpath.nodes(dataset.json, "$..CI_Responsibility[*]"))
        .concat(
            jsonpath.nodes(
                dataset.json,
                "$..CI_Responsibility[?(@.party.CI_Organisation)]"
            )
        )
        .filter(obj => !obj.path.includes("thesaurusName"))
        .map(obj => obj.value);
}
github Azure / azure-openapi-validator / src / typescript / azure-openapi-validator / rules / utilities / resourceUtils.ts View on Github external
public getCollectionModels() {
    const collectionModels = new Map()
    const doc = this.innerDoc
    const allOfResources = this.getAllOfResources()

    for (const resourceNode of nodes(doc, "$.definitions.*")) {
      for (const arrayNode of nodes(resourceNode.value, "$..[?(@.type == 'array')]")) {
        const arrayObj = arrayNode.value
        const items = arrayObj?.items
        if (items && items.$ref) {
          const itemsModel = this.stripDefinitionPath(items.$ref)
          if (allOfResources.indexOf(itemsModel) !== -1) {
            collectionModels.set(resourceNode.path[2] as string, this.stripDefinitionPath(items.$ref))
          }
        }
      }
    }
    return collectionModels
  }

jsonpath

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

MIT
Latest version published 4 years ago

Package Health Score

70 / 100
Full package analysis