json icon indicating copy to clipboard operation
json copied to clipboard

Feature request: Make it possible to require JS files of functions (like _.js)..

Open IsmailM opened this issue 10 years ago • 2 comments

It would be nice if it was possible to require a file of JS functions (perhaps something like underscore.js) which you could then use inside the -e argument...

Thanks

IsmailM avatar Jun 18 '15 15:06 IsmailM

This would be super useful for me, so I can stay using the CLI. I was trying to generate a UUID for each feature in an array called features on the root object.

json -I -f something.json -e 'this.features.forEach((f, i) => { this.features[i].id = require('uuid/v4')(); })'

craiggoldstone avatar Aug 26 '17 17:08 craiggoldstone

Yeah, totally agree - would make life easier....

I requested this back in 2015 - so I don't think there are plans to bring in this feature... And I've kind of moved onto jq (https://stedolan.github.io/jq/)

Since I had nothing better to do, I tried to doing the uuid thing with jq (@craigsnyders)....

# Create a fake features json file
echo '{"features": ["1","2","3","4"]}' > features.json

# install uuid dependency - command line tool for creating uuids
npm install -g uuid

# create a uuid json file - create uuids for each element in the features array
## first jq - just iterate over features array
## xargs - create a uuid for each one
## read that back into jq as a raw string, split by new line and then splice the array (to remove the last empty element) then loop over it to store just the uuids as strings
cat features.json | jq  '.features[]' | xargs -Iz uuid |  jq -sR 'split("\n") | .[:-1] | .[]' > uuid.txt

# Zip the features.json and uuid.json - couldn't find a simplier way of doing this...
## use slurpfile to assign uuid.json to $values - it's slurped each line into an array called $values
## set the .features array as $keys
## then do some zipping magic (copied from another github question with a minor change - https://github.com/stedolan/jq/issues/675)
cat features.json | jq --slurpfile values uuid.txt ' .features as $keys | reduce range(0; $keys|length) as $i  ( {}; . + { ($keys[$i] |tostring ): $values[$i] })'

# {
#   "1": "12b2e243-f51b-442c-873c-3c5178c1df40",
#   "2": "d226b0ed-d4db-433c-8569-a2dff0882ffd",
#   "3": "b224e5eb-771a-433c-9786-452ead884627",
#   "4": "73692bb1-6d00-4944-a96a-d53b66ab3232"
# }

Yep - should be alot more simpler...

IsmailM avatar Aug 26 '17 18:08 IsmailM