简体   繁体   中英

how to replace part of json string

I want to remove only the character "C" keys starts with C_ in the below Json String. heere is javscript object I am having

var jsonData=
{
key1:val1,
key2:val2,
C_100:1,
C_101:2,
C_102:3,
}

I am expecting the out put to be similar like

var jsonData=
{
key1:val1,
key2:val2,
100:1,
101:2,
102:3,
}

The json string is dynamic and I can have many key value pairs. i want to remove "C_" from all the keys starting with "C_".Please let me know how to remove C_ from the object.

I tried to convert using json.stringify and replace but its not working.

var jstring = JSON.stringify(jsonData);
 var y = jstring.replace("\"C_\":", "\"\":");

out put I am getting is

"{"key1":"val1","key2":"val2","C_100":"1","C_101":"2","C_102":"3"}"

Expecting out put as

"{"key1":"val1","key2":"val2","100":"1","101":"2","102":"3"}".

Lets assume you have

var jsonData=
{
key1:'val1',
key2:'val2',
C_100:1,
C_101:2,
C_102:3,
}

Then you need to process it as following

Object.entries(jsonData).map(e => [e[0].replace(/^C_/,''), e[1]]).reduce((p,n) => ({ ...p, [n[0]]: n[1] }), {})

To get

{100: 1, 101: 2, 102: 3, key1: "val1", key2: "val2"}

Here's a simple and easy to read code to do that:

var jsonData=
{
key1:"val1",
key2:"val2",
C_100:1,
C_101:2,
C_102:3,
}

var modifiedData = {};

for (key of Object.keys(jsonData)) {
  var newKey = key.replace("C_", "");
  modifiedData[newKey] = jsonData[key];
}

console.log(modifiedData) // prints var jsonData=
{
key1:"val1",
key2:"val2",
C_100:1,
C_101:2,
C_102:3,
}

var modifiedData = {};

for (key of Object.keys(jsonData)) {
  var newKey = key.replace("C_", "");
  modifiedData[newKey] = jsonData[key];
}

console.log(modifiedData) // prints { '100': 1, '101': 2, '102': 3, key1: 'val1', key2: 'val2' }

You can do it using just JSON.stringify() and JSON.parse() methods:

let jsonData =
  {
  key1: val1,
  key2: val2,
  C_100: 1,
  C_101: 2,
  C_102: 3,
};

let string = JSON.stringify(jsonData);

string = string.replace(/C_/g, "");

let obj = JSON.parse(string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM