如何在json数组中使用json对象的json模式确保字母顺序?

时间:2018-05-16 11:25:00

标签: arrays json jsonschema

我想确保json数组中的json对象由具有json模式的特定属性正确排序。

这可能吗?如果是这样,我怎样才能创建这样的json架构?

架构:

{
  "type": "object",
  "properties": {
    "cities": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "shortName": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "showInMap": {
            "type": "boolean"
          },
          "active": {
            "type": "boolean"
          }
        },
        "??ORDERBY??": "shortName",
        "??ORDER??": "ASC",
        "required": [
           "shortName"
        ]
      }
    }
  }
}

我想过滤掉未正确排序的json个文件。 示例:(无效)

{
  "cities": [
    {
      "shortName": "NY",
      "name": "New York",
      "showInMap": true,
      "active": true
    },
    {
      "shortName": "LD",
      "name": "London",
      "showInMap": true,
      "active": false
    },
    {
      "shortName": "MO",
      "name": "Moscow",
      "showInMap": false,
      "active": false
    }
  ]
}

接受正确排序的json个文件。 示例:(有效)

{
  "cities": [
    {
      "shortName": "LD",
      "name": "London",
      "showInMap": true,
      "active": false
    },
    {
      "shortName": "MO",
      "name": "Moscow",
      "showInMap": false,
      "active": false
    },{
      "shortName": "NY",
      "name": "New York",
      "showInMap": true,
      "active": true
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

编辑:此答案不使用json schema

这是处理样本数据的最小解决方案。它对于制作是不安全的,因为它缺少对undefined的各种检查,但我认为你可以随意增强它。



function isSorted(array, sortKey) {
  return array.reduce((ordered, item, index) => {
    return index > array.length - 2 ? ordered : ordered && item[sortKey] < array[index + 1][sortKey];
  }, true);
}

const incorrectCase = [{
    "shortName": "NY",
    "name": "New York",
    "showInMap": true,
    "active": true
  },
  {
    "shortName": "LD",
    "name": "London",
    "showInMap": true,
    "active": false
  },
  {
    "shortName": "MO",
    "name": "Moscow",
    "showInMap": false,
    "active": false
  }
]

const correctCase = [{
    "shortName": "LD",
    "name": "London",
    "showInMap": true,
    "active": false
  },
  {
    "shortName": "MO",
    "name": "Moscow",
    "showInMap": false,
    "active": false
  }, {
    "shortName": "NY",
    "name": "New York",
    "showInMap": true,
    "active": true
  }
];

console.log('incorrect case: ', isSorted(incorrectCase, "shortName"));
console.log('correct case: ', isSorted(correctCase, "shortName"));
&#13;
&#13;
&#13;