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
2 Answers
Reset to default 2To 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
评论列表(0条)