使用JavaScript替换字符串中的值

时间:2016-04-22 21:42:19

标签: javascript json

我想使用JavaScript将以下JSON字符串中的所有字符串值替换为空字符串,true为false,并将数组中的1到0替换为方括号。

添加信息:JSON字符串放在字符串类型变量中。

注意:属性是动态的。意思是有时我可以使用MobilePhone,并且会出现缺少此属性的情况。因此,引用属性名称不是一种选择。

我的JSON字符串:

{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}

预期结果:

{"MobilePhone":false,"ToDeleteIndex":1,"BusinessPhone":false,"ApplicantType":"","Title":"","FirstName":"","RemoveApplicant":[0,null]}

3 个答案:

答案 0 :(得分:0)

JSON.parse之后,试试这个:

const data = {
    "MobilePhone": true,
    "ToDeleteIndex": 1,
    "BusinessPhone": true,
    "ApplicantType": "HOLDER",
    "Title": "Mr",
    "FirstName": "Andrew",
    "RemoveApplicant": [1, null]
  }
  //string to empty string, true to false, and 1 to 0 (in array)
trans = {
  string: function(x) {return x= ''},
  boolean: function(x) {
    if (x)
      x = false;
    return x;
  },
  object: function(x) {
    if (Array.isArray(x))
      x.map(function(z) { if (z === 1) z = 0; return z});
    return x;
  }
}

const r = Object.keys(data).map(function(x) {
  const val = trans[typeof(data[x])] ? trans[typeof(data[x])](data[x]) : data[x];
  return {[x]: val};
})
console.log(r)

答案 1 :(得分:-1)

试试这个DEMO



var data = JSON.parse('{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}');

for (prop in data) {
  if (data[prop] === true) {
    data[prop] = false;
  } else if (typeof data[prop] == 'string') {
    data[prop] = '';
  } else if (Array.isArray(data[prop])) {
   data[prop] = data[prop].map(function(el) { return (el == 1) ? el = 0 : el});
  }
}

document.write(JSON.stringify(data));




答案 2 :(得分:-1)

您可以在javascript中使用string Replace()功能。

如果你的Json是一个字符串变量,那就做这样的事情;

var str = "{'MobilePhone':true,'ToDeleteIndex':1}";//your json as string
var res = str.replace(new RegExp("true", 'g'), "false"); //replace true to false
var res = res.replace(new RegExp("1", 'g'), "0"); //replace 1 to 0
Console.Log(res); //{'MobilePhone':false,'ToDeleteIndex':0}

但是,请注意,因为此代码会将truefalse1的所有出现替换为0,而不管它们在字符串中的位置。