简体   繁体   中英

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

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?

The escape sequences at the start of your object \ 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")
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM