How to use JSON.parse reviver method to edit a certain value.
I just want to edit every key which is declared as lastname and than return the new value.
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
}
After checking for the special case(s), you simply need to pass back unmodified values by default:
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
return value; // < here is where un-modified key/value pass though
}
JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}"
Related
I am trying to remove the $ symbol from the key in json object(parsed). Normal JS file I used Remove special character in json key name in nodejs this answer mentioned and it is working fine. But I tried in nodejs due to async it is not working properly. The last formed object did not contain the entire modified value. So I tried the original function which is posted in the question but I am getting callback function not found error. I am using node 10.19 version. Is there any other way I can remove the $ symbol from my json object. Please give me a working solution. Actualy I am getting the input from yml file which gets converted to json string in jenkins. And again In my code I have parsed it. If there any library to directly convert yml file to json in jenkins that will also help.
var obj = {
'blue':{
'test:"value',
'$test1':'value1',
'tiger':'cheetah_growl',
'$jan':'cool'
}
}
Normal js file
var obj_new = { '$name': 'test1', '$auth_users': 'bajali_s' };
console.log("obj.blue",obj.blue.tiger);
var str = obj.blue.tiger;
var res = str.replace("_", " ");
console.log("res",res);
obj.blue.tiger = res;
console.log("obj.blue",obj.blue.$test1);
//const obj1 = {"example1.":"sometext.","example2.":"anothertext."};
const obj2 = {};
console.log(Object.getOwnPropertyNames(obj));
const obj1 = obj_new;
console.log("__",obj1);
/* for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
} */
for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
}
console.log("==",obj2);
var newjson = JSON.stringify(obj2);
console.log(newjson);
Here is what I did to remove the extra symbol in the key and value. I went through many sites and came up with this procedure hope it helps someone. I have also made it little dynamic.
var special_char_keys = ["creationType", "vm_location", "nic_location", "vnetlocation", "rg_location"];
var elements_to_delete = ["blueprint_info", "riglet_info", "quick_links"];
for (var a = elements_to_delete.length; a >= 0; a--) {
delete cloudProperties[elements_to_delete[a]];
}
var Mainkeys = Object.keys(cloudProperties);
console.log("Mainkeys", Mainkeys);
var total_keys_cloudproperties = Mainkeys.length;
for (var j = total_keys_cloudproperties; j > 0; j--) { // main json loop starts
for (const key of Object.getOwnPropertyNames(cloudProperties)) { // getting the main json keys
var obj1 = cloudProperties[key];
var obj2 = {};
var obj3 = {};
var obj4 = {};
var obj5 = {};
var formattedarray = [];
var keys = Object.keys(cloudProperties[key]);
//console.log("inner keys", keys);
var tasksToGo = keys.length;
//console.log("key length",tasksToGo);
for (var i = tasksToGo; i > 0; i--) {
for (const key1 of Object.getOwnPropertyNames(obj1)) {
// var item = obj1.get(key1); // this will get the value in the json based on key
if (Array.isArray(obj1[key1])) { // checking whether the key has value as [{},{}]
// console.log("for jsonarray case");
var temparray = obj1[key1]; // assigning the array to temparray
for (var k = 0; k < temparray.length; k++) { // for loop for getting each object value
var obj3 = temparray[k]; // assigning the inner object to a variable
var Arraykeys = Object.keys(obj3);
// console.log("array inner keys", Arraykeys);
var tasksToGo1 = Arraykeys.length;
for (var t = tasksToGo1; t > 0; t--) {
for (const key2 of Object.getOwnPropertyNames(obj3)) {
if (special_char_keys.includes(key2)) {
var tempvalue = obj3[key2];
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
} else {
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
// obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
if (Arraykeys == tasksToGo1) {
break;
}
temparray[k] = obj4;
// console.log("temparray[k] ======================", temparray[k]);
}
}
obj5[key1] = temparray;
cloudProperties[key] = obj5;
// console.log("vm case", cloudProperties[key]);
} else {
// console.log("for normal case");
if (special_char_keys.includes(key1)) {
var tempvalue = obj1[key1];
// console.log(obj1[key1]);
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
cloudProperties[key] = obj2;
} else {
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
cloudProperties[key] = obj2;
}
//obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
// cloudProperties[key] = obj2;
}
}
}
//console.log("obj2",obj2);
//console.log("+++++++++++++++++",cloudProperties[key]);
}
if (j == total_keys_cloudproperties) {
//console.log("inside break");
break;
}
}
console.log("After removing", cloudProperties);
I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);
var myData = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';
$(document).ready(function () {
var myData = new Array();
for (i in myData) {
var item = myData[i];
var key = item[0];
var value = [item[1], item[2]];
var index = getElementindex(key);
if (index != -1) {
var element = finalArr[index];
element.value.push(value);
} else {
var newArr = new Array();
var element = {
key: "",
value: ""
};
element.key = key;
newArr.push(value);
element.value = newArr;
finalArr.push(element);
}
}
function getElementindex(key) {
for (i in finalArr) {
if (finalArr[i].key == key) return -i;
}
console.log(JSON.stringify(finalArr));
}
});
The value of myData string is overwritten when
var myData = new Array();
To convert the string into JSON object, use
myData = JSON.parse(myData);
<script>
var mstdta=[['A',453627726262,10],['A',453627726262,5],['B',453627726262,10],['B',453627726262,0],['C',453627726262,10],['C',453627726262,70]];
$(document).ready(function() {
var myArray = new Array();
for(i in mstdta){
var item=mstdta[i];
var key=item[0];
var value=[item[1],item[2]];
var index=getElementIndex(key);
if(index!=-1){
var element=myArray[index];
element.value.push(value);
}else{
var newArr=new Array();
var element={key:"",value:""};
element.key=key;
newArr.push(value);
element.value=newArr;
myArray.push(element);
}
}
function getElementIndex(key){
for(j in myArray){
if(myArray[j].key==key)
return j;
}
return -1;
}
console.log(JSON.stringify(myArray));
});
</script>
try this, eval() parse the string as actual array in JS
$(document).ready(function() {
var myData = new Array();
myDataString = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';
myData = eval(myDataString);
// code goes here
I am trying to do something crazy, I have a JSON object of all sorts of rules for my website. I have a system set up where I can write pseudo code and then it turns it into actual code. I have this working perfectly for strings, however now I need to be able to pass functions, and replace the pseudo code inside of functions, then execute the functions.
I think I am on the right track, however when I turn a function to a string it only turns the output of the functions into a string.
Here's my JSON (part of it)
customValidation: {
//compare: "(<!this!> && <!PrimeTimeDiscount!> == 200) || (<!PrimeTimeDiscount!> == 100)",
compare: function(){
return new Validator()["date"]("<!this!>", 50);
},
overrideDefault: true
}
The commented out "compare" is how I use this system for regular strings.
And below is how I handle turning "<!this!>" and "<!*!>" into values from the JSON object. It is basically the same code twice, but the one below I have started modifying for when a function is detected.
if(typeof customValidationRule != "function")
{
var string = customValidationRule.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRule;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
}
else
{
var customValidationRuleString = customValidationRule().toString();
var string = customValidationRuleString.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRuleString;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
var backToFunction = eval('(' + execCustomValidationRule + ')');
//validation = customValidationRule();
}
validation = eval(execCustomValidationRule);
I would like to know if there is a way to get all properties of 'myFields' assigned in a single statement ?
This works:
function fieldMap(namesString) {
var result = {};
var names = namesString.split(' ');
for (index in names) {
var name = names[index];
result[name] = name + '/text()';
}
return result;
}
var myFields = fieldMap('title rating author url');
myFields['cover']="#cover";
This doesn't work:
var myFields = fieldMap('title rating author url')['cover']='#cover';
If you want to change all properties of an object in a single statement, you have to write yourself a mapping method:
function fieldMap(namesString) { // Mike Lin's version
var result = {};
var names = namesString.split(' ');
for (var i=0; i<names.length; i++) {
var name = names[i];
result[name] = name + '/text()';
}
return result;
}
Object.prototype.map = function(callbackOrValue){
/* better create an object yourself and set its prototype instead! */
var res = {};
for(var x in this){
if(typeof this[x] === "function")
res[x] = this[x];
if(typeof callbackOrValue === "function")
res[x] = callbackOrValue.call(this[x]);
else
res[x] = callbackOrValue;
}
return res;
}
Then you can use
var myFields = fieldMap('title rating author url').map(function(){return '#cover'};
/* ... or ... */
var myFields = fieldMap('title rating author url').('#cover');
However, if you want to set myFields and change the value in the same step, try this:
var myFields;
(myFields = fieldMap('title rating author url'))['cover']='#cover';