Skip to content

Commit 18704c0

Browse files
committed
Add support for handling non string values in json
1 parent 1c10a29 commit 18704c0

File tree

4 files changed

+40
-2
lines changed

4 files changed

+40
-2
lines changed

index.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,15 @@ const jnestedReplace = (input, searchValue, newValue, skipKeys=[]) => {
3131
// for every element of array
3232
if (isArray(input[key])) {
3333
for (let i=0; i<input[key].length; i++) {
34+
3435
input[key][i] = jnestedReplace(input, searchValue, newValue, skipKeys);
3536
}
3637
continue;
3738
}
3839

3940
// If the key needs to be skipped.
4041
// Do not process and continue to next element
41-
if (skipKeys.indexOf(key) === -1) {
42+
if (skipKeys.indexOf(key) === -1 && isString(input[key])) {
4243
input[key] = input[key].replace(searchValue, newValue);
4344
}
4445
}
@@ -57,5 +58,11 @@ const isArray = (data) => {
5758
return data instanceof Array;
5859
};
5960

61+
// check id the data is string
62+
const isString = (data) => {
63+
return typeof data === 'string'
64+
&& Object.prototype.toString.call(data) === '[object String]';
65+
};
66+
6067

6168
module.exports = jnestedReplace;

package-lock.json

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "json-nested-replace",
3-
"version": "1.0.4",
3+
"version": "1.1.0",
44
"description": "Searches and replace values at every level of nested json ",
55
"main": "index.js",
66
"scripts": {

tests/test.js

+30
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,34 @@ describe('replace in nested json', () => {
101101
expect(replacedValue.repository.url).to.equal(INPUT_JSON.repository.url);
102102
expect(replacedValue.name).to.be.equal('jnested-replace');
103103
});
104+
it('show skip the values which are not string', () => {
105+
const input = {
106+
'name': 'json-nested-replace',
107+
'author': 'Arshad Kazmi',
108+
'number': 1234,
109+
'boolean': true,
110+
'repository': {
111+
'url': 'https://github.com/arshadkazmi42/json-nested-replace',
112+
'language': 'js',
113+
'numberString': '1234',
114+
'booleanString': 'true'
115+
}
116+
};
117+
118+
const expected = {
119+
'name': 'json-nested-replace',
120+
'author': 'Arshad Kazmi',
121+
'number': 1234,
122+
'boolean': true,
123+
'repository': {
124+
'url': 'https://github.com/arshadkazmi42/json-nested-replace',
125+
'language': 'js',
126+
'numberString': '4321',
127+
'booleanString': 'true'
128+
}
129+
};
130+
131+
const updatedInput = jnestedReplace(input, '1234', '4321');
132+
expect(updatedInput).to.be.deep.equals(expected);
133+
});
104134
});

0 commit comments

Comments
 (0)