Skip to content

Instantly share code, notes, and snippets.

@bradymholt
Last active January 21, 2021 08:25
Show Gist options
  • Save bradymholt/17cb99185c7b80b0f34a to your computer and use it in GitHub Desktop.
Save bradymholt/17cb99185c7b80b0f34a to your computer and use it in GitHub Desktop.
Ansible module to replace values in JSON files https://www.geekytidbits.com/ansible-module-modify-json/
#!/usr/bin/env node
var fs = require('fs');
var args = fs.readFileSync(process.argv[2], 'utf8');
var changed = false;
var jsonPath = null;
var json = null;
var keyValReplacementString = args.split(' ');
keyValReplacementString.forEach(function(i){
var keyVal = i.split('=');
if (!keyVal[1]) {
return;
} else if (keyVal[0].indexOf('path') == 0) {
jsonPath = stripQuotes(keyVal[1]);
}
});
if (jsonPath){
json = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
keyValReplacementString.forEach(function(i){
var keyVal = i.split('=');
if (keyVal[0].indexOf('path') == -1 && json[keyVal[0]]) {
json[keyVal[0]] = stripQuotes(keyVal[1]);
}
});
fs.writeFileSync(jsonPath, JSON.stringify(json, null, 2));
changed = true;
}
function stripQuotes(text) {
return text.replace(/["']*([^'"]+)['"]*"/g, '$1');
}
console.log(JSON.stringify({ changed: changed }));
@Manjukb
Copy link

Manjukb commented Sep 5, 2018

If value is having space then its considering only first letter . How to do that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment