skip to Main Content

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


  1. 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(‘~’,”));`

    Login or Signup to reply.
  2. You need to test for k, not object[k] on this line:

       // testing for the value
       if (object[k] === 'en' || object[k] === 'de') {
         object[k] = v.replace(/\n/g, 'n');
       }
    
       //testing for the key
       if (k === 'en' || k === 'de') {
         object[k] = v.replace(/\n/g, 'n');
       }
    
    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 (k === 'en' || k === 'de') {
          object[k] = v.replace(/\n/g, 'n');
        }
      });
      return object;
    }
    
    data = update(data);
    console.log('Data: ', data)

    Also, for what it’s worth, here’s a slimmer version of your function

    const update2 = object => {
      for (let o in object) object[o] = typeof object[o] === "string" ? object[o].replace(/\n/g, 'n') : update2(object[o])
      return object;
    }
    
    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"
            }
          }
        ]
      }
    };
    const update2 = object => {
      for (let o in object) object[o] = typeof object[o] === "string" ? object[o].replace(/\n/g, 'n') : update2(object[o])
      return object;
    }
    
    console.log('Data2: ', update2(data))
    Login or Signup to reply.
  3. Your problem because of if (object[k] === 'en' || object[k] === 'de') should be if (k === 'en' || k === 'de'):

    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 (k === 'en' || 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)
    Login or Signup to reply.
  4. The issue lies in the condition if (object[k] === 'en' || object[k] === 'de') inside your update 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:

    // Replace '\n' with 'n' in the JSON data
    function update(object) {
      Object.keys(object).forEach(function (k) {
        var v = object[k];
        if (v && typeof v === 'object') {
          return update(v);
        }
        if (k === 'en' || 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);
    

    Now when you run the code, it will correctly replace \n with n in the nested JSON string values.

    Hope it helps

    Login or Signup to reply.
  5. 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

    let 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"}}]}}
    
    data = JSON.parse(JSON.stringify(data, (k,v) => 
        k === "de" && typeof v === "string" ? v.replaceAll("\n", "n") : v ))
    
    console.log(data);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search