I have nested JSON and in some string value as part of the string \n
. I need to replace it with n
and return the object.
My brain is washed, cos I’m trying it for the whole day and can’t see the error.
var data = {
"d": {
"name": "Some text",
"style": [
{
"title": {
"showtitle": true,
"en": "Need help?",
"de": "\nBrauchen Sie\nHilfe?",
"font": "Helvetica-Semibold"
}
},
{
"subtitle": {
"showtitle": true,
"en": "English Text",
"de": "\nGerman\nText",
"font": "Helvetica-Semibold"
}
}
]
}
};
// Replace '\n' with 'n' in the JSON data
function update(object) {
Object.keys(object).forEach(function (k,v) {
var v = object[k];
if (object[k] && typeof object[k] === 'object') {
return update(object[k])
}
if (object[k] === 'en' || object[k] === 'de') {
object[k] = v.replace(/\n/g, 'n');
}
console.log('Key: ',k);
console.log('Value: ',v);
});
return object;
}
data = update(data);
console.log('Data: ', data)
Why the values are not updated? Where is the error?
5
Answers
this might help.
replace n with ~n ( dummy character and replace dummy character with n
`let strv1 = ‘The ngerman?’;
let strv2 = strv1.replace(‘n’, ‘~n’).replace(‘~’,”));`
You need to test for
k
, notobject[k]
on this line:Also, for what it’s worth, here’s a slimmer version of your function
Your problem because of
if (object[k] === 'en' || object[k] === 'de')
should beif (k === 'en' || k === 'de')
:The issue lies in the condition
if (object[k] === 'en' || object[k] === 'de')
inside yourupdate
function. This condition is checking if the current property value is equal to the string'en'
or'de'
, which is not what you intended.Here’s the corrected code:
Now when you run the code, it will correctly replace
\n
withn
in the nested JSON string values.Hope it helps
You could do the transform in one line using a JSON replacer function. When the property name is "de" and the value is a string, the function replaces all "\n" with "n".
Snippet