Вывод списка путей JSON из модели схемы JSON - PullRequest
0 голосов
/ 14 января 2019

Я ищу библиотеку Javascript для перечисления возможных путей Json на основе схемы Json.

Для схемы json, как показано ниже, я хочу перечислить возможные пути json.

{
  "$id": "https://example.com/person.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Customer",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    },
    "address": {
        "type": "object",
        "city": {
            "type": "string",
        },
        "country": {
            "type": "string",
        }
    }
  }
}

Возможные пути Json: имя, фамилия, возраст, address.city и address.country

1 Ответ

0 голосов
/ 15 января 2019

Вам не обязательно нужна библиотека для этого. Вы можете использовать простую рекурсивную функцию:

var schema = {
  "$id": "https://example.com/person.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Customer",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    },
    "address": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
        },
        "country": {
          "type": "string",
        }
      }
    }
  }
};

var path = ({properties}) =>
  Object.keys(properties).reduce((acc, key) =>
    acc.concat(properties[key].type !== 'object' ? key :
      path(properties[key]).map(p => `${key}.${p}`)), []);

console.log(

  path(schema)

);
...