Skip to content

Instantly share code, notes, and snippets.

@bradymholt bradymholt/json_mode
Last active Apr 10, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.