如何检查JSON文件中的属性是否已订购?

时间:2015-07-25 13:07:34

标签: json gulp

我有一个很大的json文件经常更改(翻译值)。我需要检查这个json中的属性是否按字母顺序排序。我非常希望能够使用gulp并在CI环境中运行此检查,因此在未对属性进行排序时会报告错误。

我已经搜索过但却找不到任何东西。您是否了解处理此问题的任何现有解决方案?

1 个答案:

答案 0 :(得分:1)

您可以完全使用node.js并将其轻松地挂入您的gulp构建过程中:

var fs = require('fs');
fs.readFile("data.json", { encoding: 'utf8' }, function(err, data) {
    if (err) throw err;
    var dataObj = JSON.parse(data).mystuff;

    //check if it's ordered
    for (var i = 1; i < dataObj.length; i++) {
        if (dataObj[i].toLowerCase() < dataObj[i-1].toLowerCase()) { //note that depending on what it is you're ordering, this might need to change...
            throw new Error('THIS IS OUT OF ORDER! I TOLD YOU! I TOLD YOU!!!! KEEP IT ORDERED! AND WHAT DID YOU DO?!!! UNACCEPTABLE!!!');
        }
    }
    console.log('Ordered correctly! Good work!');
});

我用来测试它的data.json,订购不正确:

{
    "mystuff": [
      "Super",
      "Duper",
      "Happy",
      "Fun"
  ]
}

并且订购正确:

{
    "mystuff": [
      "Duper",
      "Fun",
      "Happy",
      "Super"
  ]
}

如果你想更进一步让流程自动为你重新订购文件,你可以这样做:

var fs = require('fs');
var fileName = 'data.json';
var fileOptions = { encoding: 'utf8' };
fs.readFile(fileName, fileOptions, function(err, data) {
    if (err) throw err;
    debugger;
    var dataObj = JSON.parse(data);
    var dataObjOrdered = orderObj(dataObj);
    var jsonOrdered = JSON.stringify(dataObjOrdered, null, 4);
    fs.writeFile(fileName, jsonOrdered, fileOptions, function(err) {
        if (err) throw err;
        console.log('JSON data fields are ordered huzzah!');
    });
});

/**
 * Returns an object with the same data, but with its fields ordered.
 * Note that we leave array values in the same order they're already in
 */
function orderObj(obj) {
    if (!isObject(obj)) {
        return obj;
    }

    //arrays are left alone. if you want to order them too, do it inside this block
    if (Array.isArray(obj)) {
        return obj;
    }

    //load up an array containing all our object's fields
    var fields = [];
    for (var field in obj) {
        fields.push(field);
    }

    //sort the fields alphabetically (remember to do this compare case-insensitively since utf-8 capital letters come before lowercase letters)
    fields.sort(function (a, b) {
      a = a.toLowerCase();
      b = b.toLowerCase();
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });

    //return the new object with ordered fields, recursively ordering sub objects' fields
    var result = {};
    for(var i = 0; i < fields.length; i++) {
        var field = fields[i];
        var value = obj[field];
        result[field] = orderObj(value);
    }
    return result;
}

function isObject(value) {
  // http://jsperf.com/isobject4
  return value !== null && typeof value === 'object';
}