javascript - Replace characters in a JSON - Stack Overflow

I have an JSON and I would find strings in it which are a part of the values.For instance:type: 't

I have an JSON and I would find strings in it which are a part of the values.

For instance:

type: 'this.is.a.test'

I would like to replace all 'this.is.a.' in my entire JSON that only 'test' remains.

Here is my code. But It do not work:

var old = JSON.stringify(data).replace(/"this.is.a."/g, '""'); //convert to JSON string
var d = JSON.parse(old); //convert back to array

I have an JSON and I would find strings in it which are a part of the values.

For instance:

type: 'this.is.a.test'

I would like to replace all 'this.is.a.' in my entire JSON that only 'test' remains.

Here is my code. But It do not work:

var old = JSON.stringify(data).replace(/"this.is.a."/g, '""'); //convert to JSON string
var d = JSON.parse(old); //convert back to array
Share Improve this question edited Sep 11, 2019 at 6:19 Phil 165k25 gold badges262 silver badges267 bronze badges asked Sep 11, 2019 at 6:08 mm1975mm1975 1,6555 gold badges32 silver badges54 bronze badges 2
  • 3 Why do you want to process the json as a string? Json is an object, go throught the items in it and modify the values directly. Add example json in the question. – Esko Commented Sep 11, 2019 at 6:11
  • Can you clarify the pattern you want to use for the text replace? Is there some sort of pattern? – csakbalint Commented Sep 11, 2019 at 6:11
Add a ment  | 

2 Answers 2

Reset to default 2

To do this with JSON.stringify, you should pass a replacer function which calls .replace on all strings before they get returned for stringification:

const data = {
  foo: [
    'bar this.is.a. bar',
    {
      prop: 'propVal this.is.a. propVal'
    }
  ]
};

const str = JSON.stringify(
  data,
  (key, val) => {
    if (typeof val === 'string') {
      return val.replace(/this\.is\.a\./g, '');
    }
    return val;
  }
);

console.log(JSON.parse(str));

You can loop through your JSON, and you can change the structure as you need.

Here is a working DEMO

var data = {
    a: "this.is.a. test",
    b: "test this.is.a.",
    c: "test this.is.a. test"
}

for (var prop in data) {
  data[prop] = data[prop].replace(/this.is.a./g, '')
}

console.log(data);

Here is a fiddle link, you can check console

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744997699a4605295.html

相关推荐

  • javascript - Replace characters in a JSON - Stack Overflow

    I have an JSON and I would find strings in it which are a part of the values.For instance:type: 't

    17小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信