Skip to content

add JSON.parse support for arrayOfX #28

@ORESoftware

Description

@ORESoftware

I have this code which might allow me to use JSON strings as parseable option values

the syntax that works is:

--match='["a","b","c"]'

the patchwork code that I have added to my project looks like:

var parser = dashdash.createParser({ options: options });

var opts = parser.parse(process.argv);

console.log('opts before => ', util.inspect(opts));

options.filter(function (opt) {
  return String(opt.type).startsWith('arrayOf');  
}).forEach(function (opt) {

  const n = String(opt.name || opt.names[ 0 ]).replace('-', '_');
  if (n in opts) {
    opts[ n ] = _.flattenDeep(opts[ n ].map(function (item) {
      console.log('item => ', util.inspect(item));
      try {
        return _.flatten([ JSON.parse(item) ]);
      }
      catch (err) {
        return item;
      }
    }));
  }
});

console.log('opts after => ', util.inspect(opts));

but what I get is:

opts before =>  { match_any: [ '["dog","cat"]' ],
  errors_only: false,
  _order: [ { key: 'match_any', value: '["dog","cat"]', from: 'argv' } ],
  _args: [] }
item =>  '["dog","cat"]'
opts after =>  { match_any: [ 'dog', 'cat' ],
  errors_only: false,
  _order: [ { key: 'match_any', value: '["dog","cat"]', from: 'argv' } ],
  _args: [] }

looks like to make sure this goes bug free, that I would need library support for this, because the _order property needs to match I assume.

My best guess is for this type of support is to do:

  {
    names: [ 'match-any' ],
    type: 'arrayOfString',
    useJSON: true,
    help: 'Use this to filter input to match the given JS regex',
  },

if useJSON was true, then JSON.parse would be called for each item

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions