How can I filter the JSON coming back from the npm license-checker package?

天涯浪子 提交于 2021-02-10 23:58:05

问题


I'm experimenting with the license-checker library to filter and throw on certain license types. In the README, there is an example of how to interrogate the JSON data with some unexpected characters:

var checker = require('license-checker');

checker.init({
    start: '/path/to/start/looking'
}, function(json, err) {
    if (err) {
        //Handle error
    } else {
        //The sorted json data
    }
});

However, when I look at the format of that JSON, I'm not sure how I would pull it a part to evaluate the licenses. Here's an example of the structure:

 { 'ansi-styles@1.1.0': 
     { licenses: 'MIT',
       repository: 'https://github.com/sindresorhus/ansi-styles' },
    'ansi-styles@2.1.0': 
     { licenses: 'MIT',
       repository: 'git+https://github.com/chalk/ansi-styles',
       licenseFile: '...' },
    'ansi-wrap@0.1.0': 
     { licenses: 'MIT',
       repository: 'git+https://github.com/jonschlinkert/ansi-wrap',
       licenseFile: '...' },
    ...

How can I examine that json variable passed into the checker function to compare the licenses property against a license whitelist array?


回答1:


The escape sequences at the start of your object \u001b[34m look suspiciously like ANSI escape sequences used to tell a terminal to render things in color. See this for example: How to print color in console using System.out.println?. Your code correctly dumped the license JSON when I tried it thus:

var checker = require('license-checker');

checker.init({ start: '.' }, function(json, err) {
    if (err) {
        //Handle error
    } else {
        console.log (JSON.stringify (json))
    }
});

So how would you work with the resulting JSON? Object.keys on any object extracts the (necessarily) distinct keys in the object into an array. Then a simple filter expression on the array will allow you to capture whatever is of interest to you. So for example, if you want to retain all the MIT licensed packages, you could do:

var keys = Object.keys (json)
var okPackages = keys.filter (function (e) {
        return json.hasOwnProperty (e) && (json[e].licenses === "MIT")
    });


来源:https://stackoverflow.com/questions/32634199/how-can-i-filter-the-json-coming-back-from-the-npm-license-checker-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!